#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int a[]={1,2,6,8,8,9,10};
sort(a,a+7);
int l=0;
int r=end(a)- begin(a)-1;
while (l<=r){
int midle=(l+r)/2;
if(a[midle]>=8){
r=midle-1;
}else{
l=midle+1;
}
}
cout<<"第一个等于的下标";
cout<<l<<":"<<a[l]<<endl;
l=0;
r=end(a)- begin(a)-1;
while (l<=r){
int midle=(l+r)/2;
if(a[midle]>=8){
r=midle-1;
}else{
l=midle+1;
}
}
cout<<"第一个小于的下标";
cout<<r<<":"<<a[r]<<endl;
l=0;
r=end(a)- begin(a)-1;
while (l<=r){
int midle=(l+r)/2;
if(a[midle]>8){
r=midle-1;
}else{
l=midle+1;
}
}
cout<<"最后一个等于的下标";
cout<<r<<":"<<a[r]<<endl;
l=0;
r=end(a)- begin(a)-1;
while (l<=r){
int midle=(l+r)/2;
if(a[midle]>8){
r=midle-1;
}else{
l=midle+1;
}
}
cout<<"第一个大于下标";
cout<<l<<":"<<a[l]<<endl;
}
算法从0开始 C++ 二分法
最新推荐文章于 2024-11-04 23:24:03 发布