首页 > 代码库 > c - 折半查找(二分法检索)

c - 折半查找(二分法检索)

 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         else21             r = m - 1;    22     }23     return -1;    //结束循环后,仍未找到,则表示没有.24 }25 26 27 int28 main(void) {29             // 0  1, 2, 3, 4, 5, 6, 7, 8,  930     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 }

 

c - 折半查找(二分法检索)