zoukankan      html  css  js  c++  java
  • 二分查找(Binary Search)

    1. 思想:分治。

     

    2. 前提: 

      ①存储在数组中

      ②有序排列

     

    3. 优点:比较次数少,查找速度快,平均性能好。

     

    4. 缺点:要求待查表为有序表,且插入删除困难。

     

    5. 复杂度:$O(log n)$

     

    6. C++代码实现(循环和递归两种):

     

    #include <iostream>
    using namespace std;
    
    template <typename T>
    int binary_search_loop(T *Array, T Key, int length);
    template <typename T>
    int binary_search_recursion(T *Array, T Key, int left, int right);
    
    
    // ***********************************************************************************************
    // * Clarence Liang
    // * 2016-11-09
    // * Binary Search
    // * Implement the Binary Search in Recursive and Loop Ways.
    // ***********************************************************************************************
    
    
    int main(int argc, char const *argv[])
    {
        int array[21] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
        int length = sizeof(array)/sizeof(array[0]) - 1;
        int answer;
    
        // Recursive search
        answer = binary_search_recursion(array, 13, 0, length);
        if(answer != -1) 
            cout << "Answer is " << answer + 1 << endl;
        else
            cout << "Not Found" << endl;
    
        // Loop search
        answer = binary_search_loop(array, 13, length);
        if(answer != -1) 
            cout << "Answer is " << answer + 1 << endl;
        else
            cout << "Not Found" << endl;
    
        return 0;
    }
    
    
    template <typename T>
    int binary_search_recursion(T *Array, T Key, int left, int right)
    {
        if (left <= right)
        {
            int mid = (left + right)/2;
            if (Array[mid] > Key)
                right = mid - 1;
            else if (Array[mid] < Key)
                left = mid + 1;
            else
                return mid;
            return binary_search_recursion(Array, Key, left, right);
        }
        else
            return -1;
    }
    
    template <typename T>
    int binary_search_loop(T *Array, T Key, int length)
    {
        int left = 0; int right = length;
        while(left <= right)
        {
            int mid = (left + right) / 2;
            if (Array[mid] > Key)
                right = mid - 1;
            else if (Array[mid] < Key)
                left = mid + 1;
            else
                return mid;
        }
    
        return -1;
        
    }

     

  • 相关阅读:
    c# 动态调用.net编写的webservices接口
    Oracle序列(Sequence)创建、使用、修改、删除
    PLSQL Developer导入Excel数据
    asp.net MVC 过滤器使用案例:统一处理异常顺道精简代码
    PowerDesigner将PDM导出生成WORD文档
    JS魔法堂:再识instanceof
    Design Pattern: Not Just Mixin Pattern
    Design Pattern: Observer Pattern
    Architecture Pattern: Publish-subscribe Pattern
    ES6 Features系列:Template Strings & Tagged Template Strings
  • 原文地址:https://www.cnblogs.com/clarenceliang/p/6627745.html
Copyright © 2011-2022 走看看