1 #include <stdio.h> 2 3 #define LEN 10 4 5 /* 6 折半查找(二分法检索). 7 */ 8 9 int 10 index_of(int *a, int k) { 11 int l = 0; 12 int r = LEN -1; 13 int m; 14 while(l <= r) { 15 m = (r + l) >> 1; //右移(即除以2). 16 if(k == a[m]) 17 return m; //找到,则直接返回下标. 18 else if(k > a[m]) 19 l = m + 1; 20 else 21 r = m - 1; 22 } 23 return -1; //结束循环后,仍未找到,则表示没有. 24 } 25 26 27 int 28 main(void) { 29 // 0 1, 2, 3, 4, 5, 6, 7, 8, 9 30 int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 19, 22}; 31 int i = index_of(a, 19); 32 printf("%d\n", i); 33 }
时间: 2024-10-01 06:15:50