#include <iostream>

using namespace std;

int BinarySearch(int List[], int value, int low, int height);

int main()
{
    int test[] = {1,2,3,4,5,6,7,8,9,11,13,15,21,32,43};
    int pos = BinarySearch(test,12,0,14);
    if(pos > 0)
        cout << "位置:" << pos << endl;
    else
        cout << "未查询到" << endl;
    system("pause");
    return 0;
}

int BinarySearch(int List[], int value, int low, int height)
{
    if(low <= height)
    {
        int mid = (low + height)/2;
        if(List[mid] < value)
            return BinarySearch(List, value, mid+1, height);
        else if(List[mid] > value)
            return BinarySearch(List, value, low, mid-1);
        else
            return mid;
    }
    return -1;
}

 在递归传参数时候,mid一定左移一个数或者右移一个数,否则递归在查询不在搜索数组中的数时候不结束,出错。

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