对已排列好的非递减数组进行查找。
(1)非递归算法:
#include <iostream> #include<cstdlib> using namespace std; template <typename Type> int binarySearch(Type a[], const Type &x, int n) { int low = 0; int high = n - 1; int middle; while(low <= high){ middle = (low + high) / 2; if(x == a[middle]) return middle; if(x > a[middle]) low = middle + 1; else high = middle - 1; } return -1; } int main() { int a[10] = {1, 3, 5, 7, 9, 11, 13,14,20, 30}; cout<<binarySearch(a, 9, 10)<<endl; system("pause"); }