zoukankan      html  css  js  c++  java
  • 3.11 程序改错

    问题:

    二分查找的错误代码:

    int bisearch(char** arr, int b, int e, char* v)
    {
        int minIndex = b, maxIndex = e, midIndex;
        while(minIndex < maxIndex)
        {
            midIndex = (minIndex + maxIndex) / 2;
            if (strcmp(arr[midIndex], v) <= 0)
            {
                minIndex = midIndex;
            }
            else
            {
                maxIndex = midIndex - 1;
            }
        }
        if(!strcmp(arr[maxIndex], v))
        {
            return maxIndex;
        }
        else
        {
            return -1;
        }
    }


    递归程序要注意三方面问题:初始条件、转化、终止条件。针对上面这个程序,我们考虑如下:

    第一个问题:midIndex = (minIndex + maxIndex) / 2;

    可能溢出,最好改成:midIndex = minIndex + (maxIndex - minIndex) / 2;

    第二个问题:循环终止条件可能无法到达,比如minIndex = 2, maxIndex = 3, 而arr[minIndex] <= v的时候,程序将进入死循环。


    修改后代码如下:

    int bisearch(char** arr, int b, int e, char* v)
    {
        int minIndex = b, maxIndex = e, midIndex;
        while(minIndex < maxIndex - 1)
        {
            midIndex = minIndex + (maxIndex - minIndex) / 2;
            if (strcmp(arr[midIndex], v) <= 0)
            {
                minIndex = midIndex;
            }
            else
            {
                maxIndex = midIndex;
            }
        }
        if(!strcmp(arr[maxIndex], v))
        {
            return maxIndex;
        }
        else if(!strcmp(arr[minIndex, v]))
        {
            return minIndex;
        }
        else
        {
            return -1;
        }
    }


  • 相关阅读:
    syslog+rsyslog+logstash+elasticsearch+kibana搭建日志收集
    行为型模式(一)
    spring cloud Sleuth
    Java面试题(基础)
    Java笔试题
    Idea创建SpringBoot项目整合Hibernate
    Java中遍历Map的四种方式
    SQL面试题
    Linux入门
    Spring Boot AOP Demo
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3297029.html
Copyright © 2011-2022 走看看