文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>二分搜索

二分搜索

时间:2010-11-29  来源:microsoftmvp

#include<iostream>
using namespace std;

//前置条件:数组a已经排序,left和right是搜索区间的开始和结束位置,X为要查找的元素

//后置条件:若搜索成功,返回X在数组a中的索引,否则,返回-1
int BinarySerch(int *a,int left,int right,int X);
int main()
{
 int a[]={1,2,3,4,5,6,7,8,9,10};
 cout<<BinarySerch(a,0,9,5)<<endl;
 cout<<BinarySerch(a,-1,9,10)<<endl;
 cout<<BinarySerch(a,0,9,11)<<endl;
 system("PAUSE");
 return 0;
}
int BinarySerch(int *a,int left,int right,int X)
{
 if(a==NULL||left<0)return -1;
 int mid;
 while(left<=right)
 {
  mid=(left+right)>>1;
  if(a[mid]==X)return mid;
  else if(a[mid]<X) left=mid+1;
  else right=mid-1;
 }
 return -1;
}

相关阅读 更多 +
排行榜 更多 +
坦克冒险大师安卓版

坦克冒险大师安卓版

策略塔防 下载
枪战大乱斗2

枪战大乱斗2

飞行射击 下载
猎鸭挑战安卓版

猎鸭挑战安卓版

飞行射击 下载