zoukankan      html  css  js  c++  java
  • 七、递归-折半查找

    #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一定左移一个数或者右移一个数,否则递归在查询不在搜索数组中的数时候不结束,出错。

  • 相关阅读:
    mtu
    OC2_使用系统协议
    OC1_协议语句
    Json文件/网址解析
    文件归档
    Plist文件
    NS-Date/NSDateFormatter
    OC10_文件练习
    OC9_文件操作
    OC8_NSData
  • 原文地址:https://www.cnblogs.com/gongyan/p/4325991.html
Copyright © 2011-2022 走看看