C++版基本算法2--折半查找

//折半查找算法
#include <iostream>
using namespace std;
int search(int a[],int n,int x);  //函數聲明
int main()
{
int i,x,z;
int a[10];
cout<<"Please enter 10 numbers:"<<endl;
for(i=0;i<10;i++)   //輸入10個整數
cin>>a[i];
cout<<"Please enter your search number:"<<endl;
cin>>x;  //輸入要查找的數字
z=search(a,10,x);
if(!z)  //equal if(z==0)
cout<<"The number you search is not in a[i]!"<<endl;
else
cout<<x<<" is "<<z<<"th number in a[i]."<<endl;
return 0;
}
int search(int a[],int n,int x)  //折半查找函數
{
int low,mid,high;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==x)
return mid+1;  //返回找到的數字在數組中的位置
else if(a[mid]>x)
high=mid-1;
else
low=mid+1;
}
return 0; //如果沒找到就返回0
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章