对分查找

来源:互联网 发布:长治日报网络电子版 编辑:程序博客网 时间:2024/05/23 19:15

对分查找的前提是:数据已经经过排序。比较的简单,直接看代码:若找到,则返回它的小标,否则的话返回-1;

 

前提要求 num是由小到大排序好的。  // 关于排序的算法,后面会给出

int halfSearch(const int num[], const int N,int value)
{
 int left =0;
 int right = N-1;
 int center;
 while(left<=right)
 {
  center = (left+right)/2;
  if(value == num[center])
   return center;
  else if(value >num[center])
  {
   left = center +1;
  }
  else
  {
   right = center -1;
  }
 }
 return -1;
}

 

加油!