折半查找
全部代码
1 #include <stdio.h>
2 #include <assert.h>
3
4 int BinarySearch(int arr[], int len, int key)
5 {
6 int low;
7 int high;
8 int mid;
9
10 assert(arr!=NULL && len>0);
11
12 low = 0;
13 high = len-1;
14
15 while(low <= high)
16 {
17 mid = (low+high)/2;
18 if(key < arr[mid])
19 {
20 high = mid-1;
21 }
22 else if(key > arr[mid])
23 {
24 low = mid+1;
25 }
26 else
27 {
28 return mid;
29 }
30 }
31
32 return -1;
33 }
34
35 int main(void)
36 {
37 int arr[] = {1, 2, 3, 4, 5, 6, 7};
38 int len = sizeof(arr)/sizeof(arr[0]);
39 printf("%d\n", BinarySearch(arr, len, 6));
40
41 return 0;
42 }