二分搜尋又稱折半搜尋,優點是比較次數少、速度快、平均表現佳;缺點是要求資料必須有序,且不利於插入與刪除。因此它最適合「不常變動、但查詢頻繁」的有序序列。
假設表中元素按升冪排列:先取中間位置的記錄與目標關鍵字比較,相等即搜尋成功;否則以該中間位置把表切成前後兩個子表——若中間值大於目標,就往前半表繼續找,反之往後半表。重複這個過程,直到找到符合的記錄,或子表不存在(搜尋失敗)為止。
#include <iostream>
#include <stdlib.h>
#define ERROR -1
#define LEN 10
using namespace std;
/************************************************************************/
/* T 自訂資料型別
value 要查找的值
low 左側邊界(一般為 0)
high 右側邊界(一般為陣列長度 - 1)
/************************************************************************/
template <class T>
int binarySearch(T table[], T value, int low, int high) {
if (low <= high) { // 邊界有效
int mid = (low + high) / 2; // 找中間點
if (table[mid] == value) {
return mid; // 命中,回傳索引
} else if (table[mid] > value) {
// 中間值較大,目標在左半邊
return binarySearch(table, value, low, mid - 1);
} else {
// 目標在右半邊
return binarySearch(table, value, mid + 1, high);
}
}
return ERROR;
}
/************************************************************************/
/* 上邊界與下邊界其實就是陣列的起訖位置,因此可再包一層更簡潔的介面 */
/************************************************************************/
template <class T>
int binarySearch(T table[], int n, T value) {
return binarySearch(table, value, 0, n - 1);
}
template <class T>
void print(T table[], int n) {
for (int i = 0; i < n; i++) {
cout << table[i] << " ";
}
cout << "\n";
}
int main(void) {
int array[LEN] = {0};
for (int i = 0; i < LEN; i++) {
array[i] = i + 10; // 建立已排序的陣列
}
cout << "您要查找的序列為:";
print(array, LEN);
cout << "請輸入你要查找的內容:";
int search;
cin >> search;
int searchResult = binarySearch(array, LEN, search);
if (searchResult == ERROR) {
cout << "找不到 " << search << endl;
} else {
cout << "查找內容為 " << search
<< " 在指定陣列的第 " << (searchResult + 1) << " 處" << endl;
}
system("pause");
return 1;
}
(low + high) / 2 有整數溢位的風險,改成 low + (high - low) / 2 更安全。