給一個嚴格遞增數列,函數int Search_Bin(SSTable T, KeyType k)
用來二分地查找k在數列中的位置。
函數接口定義:
int Search_Bin(SSTable T, KeyType k)
其中T是有序表,k是查找的值。
裁判測試程序樣例:
#include <iostream>
using namespace std;
#define MAXSIZE 50
typedef int KeyType;
typedef struct
{ KeyType key;
} ElemType;
typedef struct
{ ElemType *R;
int length;
} SSTable;
void Create(SSTable &T)
{ int i;
T.R=new ElemType[MAXSIZE+1];
cin>>T.length;
for(i=1;i<=T.length;i++)
cin>>T.R[i].key;
}
int Search_Bin(SSTable T, KeyType k);
int main ()
{ SSTable T; KeyType k;
Create(T);
cin>>k;
int pos=Search_Bin(T,k);
if(pos==0) cout<<"NOT FOUND"<<endl;
else cout<<pos<<endl;
return 0;
}
/* 請在這裏填寫答案 */
輸入格式:
第一行輸入一個整數n,表示有序表的元素個數,接下來一行n個數字,依次爲表內元素值。 然後輸入一個要查找的值。
輸出格式:
輸出這個值在表內的位置,如果沒有找到,輸出"NOT FOUND"。
輸入樣例:
5
1 3 5 7 9
7
輸出樣例:
4
輸入樣例:
5
1 3 5 7 9
10
輸出樣例:
NOT FOUND
正確版本
int Search_Bin(SSTable T, KeyType k)
{
int low = 1, high = T.length, mid;
while(low<=high)
{
mid = (low + high) / 2;
if (T.R[mid].key > k)
high = mid - 1;
else
if (T.R[mid].key < k)
low = mid + 1;
else
{
return mid;
}
}
return 0;
}
解釋說明
折半查找的基本思想是:在有序表中,取中間記錄作爲比較對象,若給定值與中間記錄的關鍵字相等,則查找成功;若給定值小於中間記錄的關鍵字,則在中間記錄的左半區繼續查找;若給定值大於中間記錄的關鍵字,則在中間記錄的右半區繼續查找。不斷反覆,直到查找成功;或者直到最後都沒有找到,查找失敗。
流程十分簡單,具體代碼見上。