1 #include<stdio.h> 2 3 int search(int key, int a[], int len); 4 int main(void) 5 { 6 int a[] = { 1,3,6,7,8,9,10,11,13 }; 7 int k = 11; //需要找的数 8 int r = search(k, a, sizeof(a) / sizeof(a[0])); 9 10 printf("%d", r); 11 12 return 0; 13 } 14 15 int search(int key, int a[], int len) 16 { 17 int ret = -1; 18 19 int left = 0; 20 int right = len - 1; 21 while (left < right) 22 { 23 int mid = (left + right) / 2; 24 if (key == a[mid]) 25 { 26 ret = mid; 27 break; 28 } 29 else if (key < a[mid]) 30 { 31 right = mid - 1; 32 } 33 else 34 { 35 left = mid + 1; 36 } 37 } 38 39 return ret; 40 }