二分查找(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;
    
}

 

posted @ 2017-03-27 17:21  Clarence的笔记  阅读(391)  评论(0编辑  收藏  举报