编程之美:无差错二分查找

1.虽然二分查找是十分简单的程序,但是因为循环等操作也是最容易出错的,其中在写循环(或者递归)程序的时候,应该特别注意三个方面的问题:初始条件、转化、终止条件。

2.二分查找源码

int biseach(char** arr, int b, int e, char* v)
{
    int minIndex = b, maxIndex = e, midIndex;
    
    while(minIndex < maxIndex - 1)                           //若改为minIndex < maxIndex时,容易出现死循环 
    {                                                        //eg:minIndex=2 maxIndex=3时就进入死循环 
          midIndex = minIndex + (maxIndex - minIndex) / 2;   //若midIndex =(minIndex + maxIndex)/2,在上溢的时候,会导致midIndex. 
          if(strcmp(arr[midIndex], v) <= 0)
          {
              minIndex = midIndex;
          }
          else
          {
              maxIndex = midIndex;                 
          }
    }                                                       //退出循环时:若minIndex为偶数则minIndex==maxIndex,
//否则就是minIndex == maxIndex - 1
if(!strcmp(arr[maxIndex], v)) { return maxIndex; } else if(!strcmp(arr[minIndex], v)) { return minIndex; } else { return -1; } }
原文地址:https://www.cnblogs.com/biyeymyhjob/p/2645124.html