1. 程式人生 > 實用技巧 >題解 CF9B 【Running Student】

題解 CF9B 【Running Student】

陣列 : 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; } } }