int binarySearch(const int array[], int first, int last, int value)
其中,形參 array 是要查詢的陣列,形參 first 儲存了查詢範圍(即要查詢的陣列的一部分)中第一個元素的下標;形參 last 儲存了查詢範圍中最後一個元素的下標;形參 value 儲存了要查詢的值。如果在陣列中找到了 value,則該函數將返回 value 的下標,否則返回 -1。int binarySearch(const int array[], int first, int last, int value) { int middle; //查詢的中間點 if (first > last) // 基本情況 return -1; middle = (first + last) / 2; if (array[middle] == value) return middle; if (array[middle] < value) return binarySearch(array, middle+1,last,value); else return binarySearch(array, first,middle-1,value); }下面的程式演示了該函數:
//This program demonstrates a recursive function that performs a binary search on an integer array. #include <iostream> using namespace std; //Function prototype int binarySearch(const int array[], int first, int last, int value); const int SIZE = 20; int main() { int tests[SIZE] = {101, 142, 147, 189, 199, 207, 222, 234, 289, 296, 310, 319, 388, 394, 417, 429, 447, 521, 536, 600}; int result; // Result of the search int empID; // What to search for cout << "Enter the Employee ID you wish to search for: "; cin >> empID; result = binarySearch(tests, 0, SIZE-1, empID); if (result == -1) cout << "That number does not exist in the array.n"; else { cout << "That ID is found at element " << result; cout << " in the arrayn"; } return 0; } int binarySearch(const int array[], int first, int last, int value) { int middle; // Mid point of search if (first > last) // Base case return -1; middle = (first + last)/2; if (array[middle]==value) return middle; if (array[middle]<value) return binarySearch(array, middle+1,last,value); else return binarySearch (array, first,middle-1, value); }程式輸出結果:
Enter the Employee ID you wish to search for: 521
That ID is found at element 17 in the array