接着上一篇,其实不用递归进行二分查找也很简单,当时咋就没想起来呢。。
OK废话少说, show me the code
1 #include <stdio.h> 2 3 int binary_search_no_recursion(int a[], int left, int right, int key){ 4 while(left<=right){ //attention!!! 5 int mid = (left+right)/2; 6 if(key > a[mid]) 7 left = mid + 1; //attention!!! 8 else if(key < a[mid]) 9 right = mid -1; //attention!!! 10 else 11 return mid; 12 } 13 14 return -1; 15 } 16 17 int main(){ 18 int a[6]={1,2,3,4,5,6}; 19 20 printf("%d ", binary_search_no_recursion(a, 0, 5, 6)); 21 printf("%d ", binary_search_no_recursion(a, 0, 5, 8)); 22 printf("%d ", binary_search_no_recursion(a, 0, 5, 0)); 23 24 return 0; 25 }
同样要注意下一级的左右区间,要能退出查找的循环