二分查找
来源:互联网 发布:读电子书软件 编辑:程序博客网 时间:2024/06/06 19:04
一种很常用的加快查找速度的方式,二分,解决排好序的数组中的大于x的最小(第一个数)的下标。
代码实现:
#include <iostream>#include <algorithm>#include <cstring>using namespace std;int n,x;int data[1000005];int erfen(){ int low=0,high=n-1; int mid; while(low<=high) { mid=(low+high)/2; if(data[mid]==x) { //cout<<"mid= "<<mid<<endl; return mid; } else if(data[mid]>x) { //cout<<"low= "<<low<<endl; high=mid-1; } else { //cout<<"high= "<<high<<endl; low=mid+1; } } return high;}int main(){ while(cin>>n>>x) { memset(data,0,sizeof(data)); for(int i=0;i<n;i++) { cin>>data[i]; } int ans=erfen(); cout<<ans+1<<endl; } return 0;}
阅读全文
0 0
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 二分查找
- 4.客户端端接入文档
- 使用Spark SQL 探索“全国失信人数据”
- MYSQL设置编码
- 阻塞IO和非阻塞IO的区别(转载)
- mysql远程无法连接数据库的问题
- 二分查找
- JFinal -spring整合的代码
- spark maxResultSize
- 基于easyui利用poi技术实现导出,导入,导出text功能
- 5.常见概念和问题
- Unity5.6大规模地形—地形资源的创建(2)
- c++之智能指针
- 手机变身高清摄像头 DroidCamX完全使用教程
- 第十二单元练习题