1. 折半查找
#include <stdio.h> #include <stdlib.h> #define LEN_ARRAY 10 int binsearch(int *array, int len, int n) { int low=0, high=len, mid; while(low < high) { mid = (low+high)/2; if(n > array[mid]) low = mid + 1; if(n < array[mid]) high = mid – 1; if(n == array[mid]) return mid; } return -1; } int main(void) { int array[LEN_ARRAY]; int i,n; int num_search = 8; for(i=0; i<LEN_ARRAY; i++) { array[i] = i*32; } n = binsearch(array, LEN_ARRAY, num_search); if( -1 == n) { printf(“not find/n”); return 0; } if(array[n] == num_search) { printf(“find array[%d]== %d/n”, n, num_search); } return 0; }