//二分查找 intbinSearch(int* list, int n, int x) { int lo = 0, hi = n - 1; while (lo <= hi) { //int mid = (lo + hi) / 2;//此句代码在min和max很大时,会出现溢出! int mid = (lo + ((hi - lo) >> 1)); if (x > list[mid]) lo = mid + 1; elseif(x < list[mid]) hi = mid - 1; else//(x == list[mid])已找到 return mid; } return-1; }
递归形式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//二分查找(递归方式) intbinSearch_R(int* list, int lo, int hi, int x) { if (lo <= hi) { int mid = (lo + ((hi - lo) >> 1)); if (x > list[mid]) return(binSearch_R(list, mid + 1, hi, x)); elseif (x < list[mid]) return(binSearch_R(list, lo, mid - 1, x)); else//(x == list[mid])已找到 return mid; } return-1; }
测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
intmain(void) { intlist[] = {1,3,5,7,9,11,13,15,17,19};//前提:有序数组! cout << "list[]:"; for (int i = 0; i < 10;i++) cout << list[i] << " "; cout << endl;
int x = 15; //int i = binSearch(list, 10, x); int i = binSearch_R(list, 0, 10, x);
if (i < 0) cout << "未找到" << endl; elsecout << "list[" << i << "]中找到" << x << endl; return0; }