zoukankan      html  css  js  c++  java
  • 编程之美:无差错二分查找

    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; } }
  • 相关阅读:
    poj 2362 Square (dfs+剪枝)
    三种素数筛法汇总
    2009’河北省高教网络技能大赛一网站建设部分
    寒假每一天
    寒假每一天
    寒假每一天
    寒假每一天
    统计文本文件
    寒假每一天
    寒假每一天
  • 原文地址:https://www.cnblogs.com/biyeymyhjob/p/2645124.html
Copyright © 2011-2022 走看看