首页 > 代码库 > 折半查找

折半查找

 

条件: 必须是有序的元素队列

目的:查找该元素队列中是否有该元素,查找成功(找到目标元素)返回元素位置,失败(左右边界出现交叉)返回-1

int binsearch(int list[],int searchnum,int left,int right)
{
// search list[0]<=list[1]...<=list[n-1] for searchnum.
// return its position if found otherwise return -1;
 int middle;
 while(left <= right){
  middle=(left+right)/2;
  switch(COMPARE(list[middle],searchnum)){
   case -1: left=middle+1; break;
   case 0: return middle;
   case 1: right=middle-1;
  }
 }
 return -1;    
}

递归调用

int binsearch(int list[],int searchnum,int left,int right)
{
 /*search list[0]<=list[1]...<=list[n-1] for searchnum.
 return its position if found otherwise return -1;*/
 printf("\nlrm: %d %d \n",left,right);
 printf("\nlrm: %d %d \n",list[left],list[right]);
 int middle;
 if(left <= right){
  middle=(left+right)/2;
  printf("\nm ,middle: %d %d \n",middle,list[middle]);
  switch(COMPARE(list[middle],searchnum)){
   case -1: return binsearch( list, searchnum, middle+1, right) ;
   case 0: return middle;
   case 1: return binsearch( list, searchnum, left, middle-1) ;
  }
 }
 return -1;    
}

折半查找