C++编程之美-结构之法(代码清单3-18(纠正错误后的二分查找源码))

代码清单3-18(纠正错误后的二分查找源码)

int bisearch(char** arr, int b, int e, char* v)
{
     int minIndex = b, maxIndex = e, midIndex;

     // 循环结束有两种情况:
     // 若minIndex为偶数则minIndex == maxIndex;
     // 否则就是minIndex == maxIndex – 1
     while(minIndex < maxIndex - 1)	
     {
          midIndex = minIndex + (maxIndex - minIndex) / 2;
          if(strcmp(arr[midIndex] , v) <= 0 )
          {
               minIndex = midIndex;
          }
          else
          {
               // 不需要midIndex – 1,防止minIndex == maxIndex
               maxIndex = midIndex;
          }
     }
     if(!strcmp(arr[maxIndex] , v))        // 先判断序号最大的值
     {
          return maxIndex;
     }
     else if (!strcmp(arr[minIndex] , v) ) 
     {
          return minIndex;
     }
     else 
     {
          return -1;
     }
}
发布了1246 篇原创文章 · 获赞 951 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/104028194