1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <stdio.h>
int binary_search(int a[], int to_be_found, int len) { int l = 0; int r = len - 1;
while (l <= r) { int middle = l + (r - l) / 2;
if (a[middle] == to_be_found) return middle; if (a[middle] < to_be_found) l = middle + 1; else r = middle - 1; } return -1; }
int main(int argc, char *argv[]) { int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int len = sizeof(a) / sizeof(a[0]); int res = binary_search(a, 4, len); if (res != -1) printf("Find out index: %d\n", res); else printf("No answer!\n");
return 0; }
|