(續)二分查找(不用遞歸)

接着上一篇,其實不用遞歸進行二分查找也很簡單,當時咋就沒想起來呢。。spa

OK廢話少說, show me the codecode

 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\n", binary_search_no_recursion(a, 0, 5, 6));
21     printf("%d\n", binary_search_no_recursion(a, 0, 5, 8));
22     printf("%d\n", binary_search_no_recursion(a, 0, 5, 0));
23 
24     return 0;    
25 }

 

一樣要注意下一級的左右區間,要能退出查找的循環blog

相關文章
相關標籤/搜索