#include <iostream>
using namespace std;
int my_lower_bound(int *array, int size, int key)
{
int first = 0, last = size - 1;
int middle, pos = 0; //需要用pos记录第一个大于等于key的元素位置
while (first < last)
{
middle = (first + last) / 2;
if (array[middle] < key){ //若中位数的值小于key的值,我们要在右边子序列中查找,这时候pos可能是右边子序列的第一个
first = middle + 1;
pos = first;
}
else{
last = middle; //若中位数的值大于等于key,我们要在左边子序列查找,但有可能middle处就是最终位置,所以我们不移动last,
pos = last; //而是让first不断逼近last。
}
}
return pos;
}
int stl_ower_bound(int *array, int size, int key)
{
int first = 0, middle;
int half, len;
len = size;
while (len > 0) {
half = len >> 1;
middle = first + half;
if (array[middle] < key) {
first = middle + 1;
len = len - half - 1; //在右边子序列中查找
}
else
len = half; //在左边子序列(包含middle)中查找
}
return first;
}
int lower_bound(int * a, int length, int target)// find the first one larger than //target
{
int pb = 0;
int pe = length - 1;
int mid = 0;
int pos = 0;
while (pb<pe)
{
mid = (pb + pe) / 2;
if (a[mid]<target)
{
pb = mid + 1;
pos = pb;
}
else
{//a[mid]<=target ; this means a[mid] is not the answer to return;
pe = mid;
pos = pe;
}
}
// return a[pos];
return pos;
}
int low_up_bound(int * a, int length, int key, bool flag)
{
int pb = 0;
int pe = length - 1;
int mid = 0;
int pos = 0;
while ( pb < pe )
{
mid = (pb + pe) / 2;
if (a[mid] == key)
{
if (flag)
{//upper_bound;
pb = mid + 1;
//pb = mid;
pos = pb;
}
else
{//lower_bound;
pe = mid;
pos = pe;
}
}
else
if (a[mid]>key)
{
pe = mid;
pos = pe;
}
else
{//a[mid]<key
pb = mid + 1;
pos = pb;
}
}
return pos;
}
int main()
{
cout << "Hello World" << endl;
//int a[7] = { 2, 4, 4, 4, 4, 8, 10 };
int a[7] = { 1, 2, 3, 4, 5, 6, 7 };
int length = sizeof(a) / sizeof(int);
cout << lower_bound(a, length, 4) << endl;
cout << stl_ower_bound(a, length, 4) << endl;
cout << my_lower_bound(a, length, 4) << endl;
cout << low_up_bound(a, length, 4, true) << endl;
cout << low_up_bound(a, length, 4, false) << endl;
return 0;
}
lower_bound upper bound
最新推荐文章于 2019-08-31 11:41:54 发布