二分查找(递归与非递归)

递归的二分查找:

 1 int search(int *a, int target, int p, int r)
 2 {
 3     if (p <= r)
 4     {
 5         int mid;
 6 
 7         mid = (p + r) / 2; 
 8         if (*(a + mid) == target)
 9             return 1;
10         else if (*(a + mid) > target)
11             return search(a, target, p, mid - 1);
12         else
13             return search(a, target, mid + 1, r);
14     }
15     return 0;
16 }

 

 

非递归的二分查找:

 1 int search(int *a, int target, int p, int r)
 2 {
 3     int mid;
 4 
 5     while (p <= r)
 6     {
 7         mid = (p + r) / 2;
 8         if (*(a + mid) == target)
 9             return 1;
10         else if (*(a + mid) > target)
11             r = mid - 1;
12         else
13             p = mid + 1;
14     }
15 
16     return 0;
17 }

 

posted @ 2014-10-30 22:04  yyxayz  阅读(162)  评论(0编辑  收藏  举报