二分查找

数组 :    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;
        }
    }
}

 

posted @ 2020-11-15 19:57  哈哈不是嘎嘎  阅读(76)  评论(0编辑  收藏  举报