二分法查找(折半查找)【有序表快速查找】

#include<iostream>
#include<algorithm>
using namespace std;
int g[20],index,n;
int Bisearch(int left,int right){
	int mid = (left + right)/2;
	if(right < left)return -1;
	if(g[mid] == index)return mid;
	else{
		if(g[mid] > index)Bisearch(left,mid - 1);
		else Bisearch(mid + 1,right);
	}
}
bool cmp1(int a,int b){
	return a < b;
}
int main(){
	cout<<"input length: "<<endl;
	cin>>n;
	cout<<"input array:"<<endl;
	for(int i = 1;i <= n;i++)cin>>g[i];
	sort(g + 1,g + n + 1,cmp1);
	cin>>index;
	int key = Bisearch(0,n);
	if(key == -1)cout<<"not"<<endl;
	else cout<<key;
}

 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页