二分查找的应用
递增序列的查找
补充:return -1的解释
#include <iostream>
using namespace std;
int s[1000];
int search(int str[],int left,int right,int num){
while(left<=right){//要不断循环查找-while:既可判断,又可循环
int mid=(left+right)/2;
if(num==str[mid])
return mid;
else if(num<str[mid])
right=mid-1;//在左边找
else left=mid+1;//在右边找
}
return -1;//非法区间
}
int main(){
int n,num;
cin>>n>>num;
for(int i=0;i<n;i++)
cin>>s[i];
cout<<search(s,0,n-1,num)<<endl;
return 0;
}
同理递减序列的查找
#include <iostream>
using namespace std;
int s[1000];
int search(int str[],int left,int right,int num){
while(left<=right){//要不断循环查找-while:既可判断,又可循环
int mid=left+(right-left)/2;//等同(left+right)/2,可避免因left与right过大而溢出的问题
if(num==str[mid])
return mid;
else if(num<str[mid])
left=mid+1;//在右边找
else right=mid-1;//在左边找
}
return -1;//非法区间
}
int main(){
int n,num;
cin>>n>>num;
for(int i=0;i<n;i++)
cin>>s[i];
cout<<search(s,0,n-1,num)<<endl;
return 0;
}
如何计算根号数的近似值
#include <cstdio>
#include<cmath>//sqrt
using namespace std;
const double eps=1e-5;
double Func(double n){//求平方的函数,求平方根
return n*n;
}
double index(double left,double right){//区间
double mid=0.0;
while(left-right>eps){
mid=(left+right)/2.0;
if(Func(mid)>right)//以mid为准,近似数在左端
right=mid;
else left=mid;
}
return mid;//相当于left与right
}
int main(){
double l,r;
scanf("%lf%lf",&l,&r);
double y=index(l,r);
printf("%.6lf",y);
return 0;
}