这是非下降序列的二分查找求下界和上界的方法,非上升序列的方法类似。
个人觉得原理就是逼近思想
//二分查找找下界(>=temp的第一个数的下标)
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int stack[1005];
int n,temp;
while(cin>>n)
{
for(int i=0;i<n;i++)
cin>>stack[i];
cin>>temp; //要查找的数
int low =0, high = n-1;
int mid;
while(low <= high)
{
mid = (low + high) / 2;
if (temp > stack[mid])
low = mid + 1;
else
high = mid - 1; //逼近左边
}
cout<<low<<endl;
}
return 0;
}
//二分查找找上界(>temp的第一个数的下标)
#include <cstring>
#include <string>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int stack[1005];
int n,temp;
while(cin>>n)
{
for(int i=0;i<n;i++)
cin>>stack[i];
cin>>temp; //要查找的数
int low =0, high = n-1;
int mid;
while(low <= high)
{
mid = (low + high) / 2;
if (temp < stack[mid])
high = mid - 1;
else
low = mid + 1; //逼近右边
}
cout<<low<<endl;
}
return 0;
}