void* BSearch(void* key, void* base, int n, int elemSize, int (*cmpfn) (void*, void*)){ int left = 0, right = n; while (left <= right) { int mid = left + (right - left)/2; void* elemAddr = (char*) base + mid*elemSize; int tmp = cmpfn(key, elemAddr); if (tmp == 0) { return elemAddr; } elseif (tmp < 0) { right = mid - 1; } else { left = mid + 1; } } returnNULL; }
说明:
left + (right - left)/2
此种写法为防止 left + right 的值过大而溢出,所以采用此种写法
写一个函数 LowerBound,在包含 size 个元素的、从小到大排序的 int 数组 a 里查找比给定整数 p 小的,下标最大的元素。找到则返回其下标,找不到则返回-1。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intLowerBound(int a[],int size,int p){ int L = 0; int R = size - 1; int lastPos = -1; //到目前为止找到的最优解 while( L <= R) { int mid = L+(R-L)/2; if(a[mid] >= p) R = mid - 1; else { lastPos = mid; L = mid + 1; } } return lastPos; }