C++ 二分查找递归和循环实现
1 //recursive 2 int binarySearch(int a[],int start,int end,int k){ 3 if(start > end) return -1; 4 int mid = start + (end -start) /2; 5 if(k == a[mid]) return mid; 6 else if(a[mid] > k) return binarySearch(a,start,mid-1,k); 7 else return binarySearch(a,mid+1,end,k); 8 } 9 //iteration 10 int binarySearch(int a[],int length,int k){ 11 int start = 0; 12 int end = length-1; 13 while(start <= end){ 14 int mid = start + (end - start)/2; 15 if(a[mid] == k) return mid; 16 else if(a[mid] >k) { 17 end = mid-1; 18 }else{ 19 start = mid+1; 20 } 21 } 22 return -1; 23 }