前提:数据先排序。

#include <iostream>

using namespace std;

int BinarySearch(int List[], const int size, const int value);

int main()
{
    int a[] = {1,2,3,4,5,6,7,8,11,23,43,123};
    int pos = BinarySearch(a,12,321);
    if(pos > 0)
        cout << "所寻找数据下标:" << pos << endl;
    else
        cout << "所寻找数据超出范围" << endl;  

    system("pause");
    return 0;
}

int BinarySearch(int List[], const int size, const int value)
{
    int low, height, mid;
    low = 0;
    height = size - 1;
    if(List[size -1] < value)
        return -1;

    mid = (low + height) / 2;
    while(low < height)
    {
        if(List[mid] > value)
        {
            mid = (low + mid) / 2;
        }
        else if(List[mid] < value)
        {
            mid = (mid + height) / 2;
        }
        else
            return mid;
    }
}

 以上代码有问题,会出错。

posted on 2015-03-10 12:26  箭已离弓  阅读(117)  评论(0编辑  收藏  举报