C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
int binary_search(
const
int arr[],
int low,
int high,
int key)
{ // 递归 int mid = (low+high)/ 2; if(low>high) return - 1; else { if(arr[mid]==key) return mid; else if(arr[mid]>key) return binary_search(arr,low,mid- 1,key); else return binary_search(arr,mid+ 1,high,key); } } int binary_search2( const int arr[], int low, int high, int key) { // 非递归 while (low <= high) { int mid = (low + high) / 2; if( key == arr[mid] ) return mid; if( key > arr[mid]) low = mid + 1; else high = mid - 1; } return - 1; } |