二分,一种常用的查找方法,时间复杂度O(log2(n)),二分的思想很重要,常常可以减小算法的时间复杂度。一开始自己只是记住了怎样去写,现在研究了一下,有了些新的体会。二分函数的写法并不是只有固定的那一套:low=0; high=n; if(a[mid]>val)high=mid-1; else if(a[mid]<val) low=mid+1; else return mid; 设置界的角度不同,跳出循环的条件就不同,low, high”指针“的变化也略有不同。
输入文件内容:
8
4 11 14 18 41 44 51 72
4 11 14 18 41 44 51 72 36 2 100
9
4 11 14 18 41 44 51 72 89
4 11 14 18 41 44 51 72 89 36 2 100
第一种:
#include <iostream>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=1000;
int n,x,a[maxn];
int midfind(){
int low=0,high=n+1,mid,count=0,depth=int(log2(n))+1;
while(high>1&&low<n){
if(count>depth)break; //查找次数不超过判定树的深度
mid=(high+low)/2;
count++;
if(a[mid]==x)return mid;
else if(a[mid]<x)low=mid;
else high=mid;
}
return 0;
}
int main(int argc, char *argv[]) {
freopen("cin.txt","r",stdin);
while(cin>>n){
int i;
for(i=1;i<=n;i++)cin>>a[i];
for(i=1;i<=n+3;i++){
cin>>x;
cout<<midfind()<<" ";
}
cout<<endl;
}
return 0;
}
输出:
1 2 3 4 5 6 7 8 0 0 0
1 2 3 4 5 6 7 8 9 0 0 0
第二种:
#include <iostream>
#include<cstdio>
using namespace std;
const int maxn=1000;
int n,x,a[maxn];
int midfind(){
int low=1,high=n,mid;
while(low<=high){ //当不能找到目标值时就会发生low>high的情况
mid=(high+low)/2;
if(a[mid]==x)return mid;
else if(a[mid]<x)low=mid+1; //跳出循环的基础
else high=mid-1;
}
return 0;
}
int main(int argc, char *argv[]) {
freopen("cin.txt","r",stdin);
while(cin>>n){
int i;
for(i=1;i<=n;i++)cin>>a[i];
for(i=1;i<=n+3;i++){
cin>>x;
cout<<midfind()<<" ";
}
cout<<endl;
}
return 0;
}
输出:
1 2 3 4 5 6 7 8 0 0 0
1 2 3 4 5 6 7 8 9 0 0 0