二分查找算法的C/C++实现

自己随便写的,如果大家有更优化的算法,希望留下评论或链接,非常感谢~~~

 int half_search(int num, int arr[], int len){
 int start = 0, end = len-1;
 int index = 0;
 while(start <= end){
  index = start + (end-start)/2;     //不用 (end+start)/2 是为了防止溢出,

// index = start + (end-start)>>1;     //这样可能更快
  if(num == arr[index]){
   printf("We found this num: %d/n", arr[index]);
   return 1;
  }else if(num > arr[index]){
   start = index + 1;
  }else{
   end = index - 1;
  }
 }
 printf("Couldn&apos;t found this num: %d/n", num);
 return 0;
}

posted @ 2008-07-21 16:57  MXi4oyu  阅读(156)  评论(0编辑  收藏  举报