二分查找的各种条件
int firstEqual(int *a, int beg, int end, int x) {// a[i-1] < x <= a[i]int s = beg - 1;int t = end + 1;while ( s + 1 < t){int mid = s + (t - s)/2;if (x > a[mid])s = mid;elset = mid;}//要返回后面的坐標, 所以要對后面的坐標進行判斷if (t == end + 1 || a[t] != x)return -1;return t;}// a[i - 1]<= x < a[i], 對前面的坐標進行判斷
int lastEqual(int *a, int beg, int end, int x) {int s = beg -1;int t = end +1;while (s +1 < t) {int mid = s + (t - s) /2;if (x >= a[mid])s = mid;elset = mid;}if (s == beg - 1 || a[s] != x)return -1;return s;
}// a[i - 1] <= x <a[i], 判斷后面的坐標
int firstBigger(int *a, int beg, int end, int x) {//找到比x大的第一個數int s = beg - 1;int t = end + 1;while (s + 1 < t) {int mid = s + (t - s)/2;if (x >= a[mid])s = mid;elset= mid;}if (t == end + 1 || a[t] <= x)return -1;return t;
}//a[i-1] < x <= a[i], 判斷前面的坐標
int lastLess(int *a, int beg, int end, int x) {//找到比x小的最后一個數int s = beg - 1;int t = end + 1;while (s +1 < t){int mid = s + (t - s)/2;if (x > a[mid])s = mid;elset = mid;}if (s == beg - 1 || a[s] >= x)return -1;return s;
}int main()
{int a[] = {1,2,2,2,2,2,5,5,5,5,5};//10int b[] = {1,3};int c[] = {1,2,5,6,6,6,6};//6int d[] = {3,4,6,6,7,7,9,10,10};//8cout<<firstBigger(a,0,10,2)<<" "<<firstBigger(a,0,10,5)<<" "<<firstBigger(a,0,10,3)<<" "<<firstBigger(a,0,10,1)<<endl;cout<<firstBigger(b,0,1,1)<<" "<<firstBigger(b,0,1,2)<<endl;cout<<firstBigger(c,0,6,2)<<" "<<firstBigger(c,0,6,5)<<" "<<firstBigger(c,0,6,3)<<" "<<firstBigger(c,0,6,6)<<endl;cout<<firstBigger(d,0,8,3)<<" "<<firstBigger(d,0,8,4)<<" "<<firstBigger(d,0,8,6)<<" "<<firstBigger(d,0,8,7)<<" "<<firstBigger(d,0,8,9)<<" "<<firstBigger(d,0,8,10)<<" "<<firstBigger(d,0,8,2)<<endl;cout<<endl;cout<<lastLess(a,0,10,2)<<" "<<lastLess(a,0,10,5)<<" "<<lastLess(a,0,10,3)<<" "<<lastLess(a,0,10,1)<<endl;cout<<lastLess(b,0,1,1)<<" "<<lastLess(b,0,1,2)<<endl;cout<<lastLess(c,0,6,2)<<" "<<lastLess(c,0,6,5)<<" "<<lastLess(c,0,6,3)<<" "<<lastLess(c,0,6,6)<<endl;cout<<lastLess(d,0,8,3)<<" "<<lastLess(d,0,8,4)<<" "<<lastLess(d,0,8,6)<<" "<<lastLess(d,0,8,7)<<" "<<lastLess(d,0,8,9)<<" "<<lastLess(d,0,8,10)<<" "<<lastLess(d,0,8,2)<<endl;return 0;
}
所有條件的二分查找只有兩種方式
1.
?mid ? ? ? ? mid
a[i-1]<x<=a[i]
? ?s ? ? ? ? ? ? t
因為t的那一邊有一個等號,所以當 a[mid] >= x時,t = mid
?1.1 返回大于等于x的第一個 return t
? 1.2 ?返回小于x的最后一個 return s
2.?
?mid ? ? ? ? mid
a[i-1]<=x<a[i]
? ?s ? ? ? ? ? ? t
因為s的那一邊有等號,所以當a[mid] <=x時,s = mid
2.1 返回小于等于x的最后一個 return s
2.2 返回大于x的第一個 return t
總結