二分查找(递归与非递归)
递归的二分查找:
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 }