您的位置:首页 > 其它

二分查找

2012-12-01 23:18 204 查看
//
//// 二分查找
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;

int biS(int *an, int s, int n)
{
int i=0, j=n-1,pos;
if ( (s-an[i])*(s-an[j])>0)
{
return 0;
}
while (i<=j)
{
pos=i+((j-i)>>1);
if(an[pos]<s)
{
i=pos+1;
}else if (an[pos]>s)
{
j=pos-1;
}else
{
return pos;
}
}
return 0;
}
int main()
{
int an[100];
int i;
for (i=0; i<100; i++)
{
an[i]=i*2;
}

sort(an,an+100);

int n;
for (i=0;i<100; i++)
{
int v=biS(an, i*2,100);
cout<<"index: "<<v<<" value:  "<<an[v]<<endl;
}

return 0;
}

1.注意i+(j-i)/2比(i+j)/2好,注意>>比/好,注意>>的优先级,必须用括号把整个>>括起来

2.注意pos=i+1,必须是i+1,否则当j-i=1是会陷入死循环。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: