二分查找
二分法查找
1 #include <stdio.h>
2 #include <stdlib.h>
3 #define N 100
4 int compare(int middle,int key)
5 {
6 if(0 > middle -key){
7 return -1;
8 }
9 else if(0 < middle - key){
10 return 1;
11 }
12 else {
13 return 0;
14 }
15 }
16 int binarySearch(const int list[],int key,int length)
17 {
18 int left=0,right=length-1,middle;
19 while(left <= right){
20 middle = (right + left)/2 ;
21 switch ( compare(list[middle],key) ){
22 case -1: left = middle+1; break;
23 case 1: right=middle-1; break;
24 case 0:return middle;
25 }
26 }
27 return -1;
28 }
29
30 int main(void)
31 {
32 int a[N]={1,2,3,4,5,6,7,8,9};
33 printf("%d
",a[binarySearch(a,2,9)]);
34 return 0;
35 }