前提是:有序序列
#include<stdio.h>
#include <iostream>
#include<iomanip>
using namespace std;
int BinSearch1(int r[],int n,int k){
int low=0;
int high=n-1;
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(k<r[mid])
high=mid-1;
else if(k>r[mid])
low=mid+1;
else
return mid;
}
return -1;
}
void main(){
int a[]={10,23,54,65,68,69,70,75,79,80,99};
int m=BinSearch1(a,11,70);
cout<<"第"<<m+1<<"个位置"<<endl;
}
时间复杂度:O(log2 n)