binary search算法特别讲究细节,微小的改动都会带来不同的结果,这篇博客将放上lower_bound和upper_bound的实现
lower_bound的实现
说明:inputs是升序排序好的数组,target是要搜索的元素
// Function to perform lower bound binary search
int lowerBound(const std::vector<int>& data, int target) {
int low = 0;
int high = data.size(); // Note: high is set to data.size() not data.size() - 1
while (low < high) {
int mid = low + (high - low) / 2;
if (data[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
return low; // Returns the index of the first element >= target
}
upper_bound的实现
// Function to perform upper bound binary search
int upperBound(const std::vector<int>& data, int target) {
int low = 0;
int high = data.size(); // Note: high is set to data.size(), not data.size() - 1
while (low < high) {
int mid = low + (high - low) / 2;
if (data[mid] <= target) {
low = mid + 1; // Move low up to exclude the current mid
} else {
high = mid;
}
}
return low; // Returns the index of the first element > target
}