我觉得要了解这两种策略,除了多刷题没别的方法。
二分搜索 #include#include int BinSerach(int a[], int first, int LEN,int j){ if(j == a[(first + LEN)/2]) return j; if(j < a[(first + LEN)/2]) return BinSerach(a, first, (first + LEN)/2, j); if(j > a[(first + LEN)/2]) return BinSerach(a, (first + LEN)/2, LEN, j); printf("no this intger\n");} int main(){ const int LEN = 1000; int a[LEN]; int i; for(i = 0; i < LEN; i++) a[i] = i; int j; printf("请输入数字:"); scanf("%d", &j); if(j > a[LEN - 1]) { printf("no seek"); exit(0); } getchar(); getchar(); j = BinSerach(a, 0, LEN - 1,j); printf("output:%d \n", j);}
这是我仿照july大神实现的一个二分搜索算法我上面写的是啥。天哪void binary_search(int arry[], int n, int value){ int left = 0; int right = n - 1; while(left <= right) { int middle = left + ((right - left)>>1); if(a[middle] < value) { left = middle + 1; } else if(a[middle] > value) { right = middle - 1; } else { return middle; } } return -1;}