折半查找(C++)
程序员文章站
2024-03-20 18:58:58
...
#include <iostream>
using namespace std;
int BinSearch(int *a,const int x,const int n);
int main()
{
int x[]={1,2,3,4,5,6,7,8,9,10};
int q,num=7;
q=BinSearch(x,num,10);
if(q<0) cout<<"没找到"<<endl;
else cout<<"在x["<<q<<"]找到"<<num<<endl;
return 0;
}
int BinSearch(int *a,const int x,const int n)
{
int left=0,right=n-1;
while(left<=right)
{
int middle=(left+right)/2;
if(x<a[middle]) right = middle-1;
else if(x>a[middle]) left=middle+1;
else return middle ;
}
return -1;
}
上一篇: Bootstrap笔记(二) 博客分类: Coding bootstrap
下一篇: 折半查找