二分法

#include "stdafx.h" int *bsearch(int *t, int n, int x); int main(int argc, char* argv[]) { int a[10] = {1,2,3,4,5,6,7,8,9,10}; int *p; p = bsearch(a, 10, 1); printf("%d/n",*p); return 0; } /* int *bsearch(int *t, int n, int x) { int lo, hi; lo = 0, hi = n; while(lo < hi) { int mid = (lo + hi) / 2;// int mid = (lo + hi) >> 1; if(x > t[mid]) lo = mid + 1; else if(x < t[mid]) hi = mid; else return t+mid; } return NULL; } */ /* int *bsearch(int *t, int n, int x) { int lo, hi; lo = 0, hi = n; while(lo < hi) { int mid = (lo + hi) / 2; int *p = t + mid; if(x > *p) lo = mid + 1; else if(x < *p) hi = mid; else return p; } return NULL; } */ int *bsearch(int *t, int n, int x) { int *lo, *hi; lo = t, hi = t + n; while(lo < hi) { int *mid = lo + ((hi - lo) >> 1); if(x > *mid) lo = mid + 1; else if(x < *mid) hi = mid; else return mid; } return NULL; }

你可能感兴趣的:(null,include)