zoukankan      html  css  js  c++  java
  • 二分查找

    数组 :    1  4  7   9   12   45   56

    [mayc@ ~/friendCode]$./test
    5
    find from 0 to 7
    find from 0 to 3
    find from 2 to 3
    find from 2 to 2
    没找到
    7
    find from 0 to 7
    find from 0 to 3
    find from 2 to 3
    第3位置
    45
    find from 0 to 7
    find from 4 to 7
    第6位置
    1
    find from 0 to 7
    find from 0 to 3
    find from 0 to 1
    第1位置
    56
    find from 0 to 7
    find from 4 to 7
    find from 6 to 7
    第7位置

    int getValue(int arry[], int posBegin, int posEnd,  int obj)
    {
        cout<< "find from " << posBegin << " to " << posEnd << endl;
       if (posBegin >= posEnd)
       {
           return -1;
       }
    
       int posMiddle = (posBegin + posEnd)/2;
    
       if (arry[posMiddle] > obj)
       {
           return getValue(arry, posBegin, posMiddle, obj);
       }
       else if ( arry[posMiddle] < obj )
       {
           return getValue(arry, posMiddle+1, posEnd, obj);
       }
    
       return  posMiddle;
    }
    
    int main()
    {
        while(1)
        {
            int obj = 0;
            cin >> obj;
    
            int val[] = { 1,4,7,9,12,45,56};
            int label = getValue(val, 0, 7, obj);
            if (label != -1)
            {
                cout << "" << label+1 << "位置" << endl;
            }
            else
            {
                cout << "没找到" << endl;
            }
        }
    }
  • 相关阅读:
    XStream
    Tomcat权威指南-读书摘要系列2
    《人性的弱点》
    HttpClient
    Spring整合Mybatis
    Tomcat权威指南-读书摘要系列1
    MT【88】抽象函数
    MT【87】迭代画图
    MT【86】两个绝对值之和最大
    MT【85】正整数系数
  • 原文地址:https://www.cnblogs.com/silentNight/p/13978621.html
Copyright © 2011-2022 走看看