折半查找法


折半查找法


int main()
{
const int n=10;
int i,number,top,bott,mid,loca,a[n];//mid用bott和top表示,方便迭代。
bool flag=true,sign;//設置布爾變量即標誌位。
char c;
cout<<“enter data:”<<endl;
cin>>a[0];
i=1;
while(i<n)
{
cin>>a[i];
if(a[i]>=a[i-1])
i++;
else
cout<<“enter this data again:”;//輸入已經排好序的數列,也可以加上冒泡排序自動排序
}
cout<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
while(flag)
{
cout<<“input number of to look for:”;
cin>>number;
sign=false;
top=0;
bott=n-1;
if((number<a[0])||(number>a[n-1]))
loca=-1;
while((!sign)&&(top<=bott))
{
mid=(bott+top)/2;
if(numbera[mid])
{
loca=mid;
cout<<“find”<<number<<",its position is"<<loca+1<<endl;
sign=true;
}
else if(number<a[mid])
bott=mid-1;//捨去後一半
else
top=mid+1;
}
if(!sign||loca
-1)
cout<<number<<“has not found”<<endl;
cout<<“continue or not”;
cin>>c;
if(c==‘n’||c==‘N’)
flag=false;
}
return 0;
}
輸入十個已經排好序的數,然後進行查找。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章