Lower_bound and Upper_bound
STL implementation of these two algorithms, but the code looks very obscure, if you want to quickly write these two algorithms, the reference to the implementation of the STL, I am afraid will be very laborious. Here, I provide a very concise implementation.
The code is for informational purposes only. Lower_bound
Given an ordered array vals, look for the subscript of the first value in the vals , not found, return-1.
Give a chestnut, Vals = [0, 1, 1, 1, 2, 3], then lower_bound should return 1.
The idea of the following algorithm is very simple, simple binary lookup, the key to the binary lookup algorithm is that each iteration, the scope of the search must be narrowed, that is, each time is either the begin forward, or the end back, if the scope does not shrink, There is a good chance that infinite iterations will occur.
Find the time there is a special attention to the place, that is, if the vals[mid] = = k, if the general binary search algorithm, now return can, but we are looking for the first K, now will end to update to Mid-1, end is nothing but two possible, or Point to a number less than K , in which case, Vals[mid] < K is always set up, plus the condition that the while terminates, the begin will eventually equal end + 1.
The other case is that the end points to the number equal to K, so that, in the next iteration, it is again updated to Mid-1, and until it points to a number that is not equal to K .
int Lower_bound (vector<int>& vals, int k) {
* * Find the first k
/int begin = 0, end = Vals.size ()-1;
while (begin <= end) {
/* Begin continuously approaching end
/int mid = (begin + End)/2;
if (Vals[mid] < k) {
begin = mid + 1;
}
else if (Vals[mid] > k) {End
= mid-1;
}
else {/* Vals[mid] = = k *
/end = Mid-1
}
}
if (Begin >= Vals.size ()) return-1;
return Vals[begin] = = k? Begin:-1;
}
Upper_bound
The Upper_bound function is used to find the subscript (scanned from left to right) of the last value equal to K in the ordered array vals , which is not found, and returns-1.
The following code is slightly different from the above, and when vals[mid] = = k, the Begin is updated to mid + 1, at which point the number of begin points is nothing more than two possibilities, one is not equal to K, in this case, the next iteration Vals[mid] > K Total is set up, plus while the recursive termination condition is begin <= end, ending is equal to begin-1.
The other is that the number of the begin point equals K, and the same is true, and in the next iteration the begin will move forward.
int Upper_bound (vector<int>& vals, int k) {
* * Find the last k
/int begin = 0, end = Vals.size ()-1;
While [begin <= end] {
int mid = (begin + End)/2;
if (Vals[mid] < k) {
begin = mid + 1;
}
else if (Vals[mid] > k) {End
= mid-1;
}
else {/* Vals[mid] = = k *
/begin = mid + 1;
}
}
if (end < 0) return-1;
return Vals[end] = = k? End:-1;
}