• 查找


    查找

    顺序查找

    • 顺序查找的基本思想:

    从序列的首元素开始,逐个元素与待查找的关键字进行比较,直到找到相等的。若整个序列中没有与待查找关键字相等的元素,就是查找不成功。

    例9-14顺序查找函数模板

    template <class T>
    int seqSearch(const T list[], int n, const T &key) {
        for(int i = 0; i < n; i++)
            if (list[i] == key)
                return i;            
        return -1;                 
    }

    折半查找(二分法查找)算法

    • 对于已按关键字排序的序列,经过一次比较,可将序列分割成两部分,然后只在有可能包含待查元素的一部分中继续查找,并根据试探结果继续分割,逐步缩小查找范围,直至找到或找不到为止。

    折半查找算法示例

    • 用折半查找法,在下列序列中查找值为21的元素:

    • 用折半查找法,在下列序列中查找值为20的元素:

    例9-15 折半查找函数模板

    template <class T>
    int binSearch(const T list[], int n, const T &key) {
        int low = 0;
        int high = n - 1;
        while (low <= high) {   
            int mid = (low + high) / 2;
            if (key == list[mid])    
                return mid; 
            else if (key < list[mid])
                high = mid – 1;
            else
                low = mid + 1;
        }
        return -1;
    }
  • 相关阅读:
    nginx:配置详细说明
    linux:/etc/rc.local 不能自动启动问题
    nginx:403 forbidden 二种原因
    nginx:虚拟主机配置
    linux:lnmp环境搭建
    php:mysqli扩展
    linux:磁盘的分割、检验、格式化与挂载
    webpack
    js的window.onscroll事件兼容各大浏览器
    js window事件解析(转载)
  • 原文地址:https://www.cnblogs.com/beautiful-code/p/4925446.html
Copyright © 2020-2023  润新知