#include <bits/stdc++.h>
using namespace std;
//二分查找递归算法
int binary_search(int *a,int begin,int end,int x){
if(begin>end)
return -1;
int mid = (begin+end)/2;
if(x==a[mid])
return mid;
else if(x<a[mid])
return binary_search(a,begin,mid-1,x);
else
return binary_search(a,mid+1,end,x);
}
//判断数组a是否有序
bool judge(int *a,int n){
bool flag = true;
for(int i=0;i<n-1;i++){
if(a[i]>a[i+1]){
flag = false;
break;
}
}
return flag;
}
//快速排序
int patartion(int *a,int left,int right){
int x = a[left];
int l = left;
int r = right+1;
while(true){
while(a[++l]<x&&l<r);
while(a[--r]>x);
if(l>=r)
break;
swap(a[l],a[r]);
}
a[left] = a[r];
a[r] = x;
return r;
}
void Quick(int *a,int begin,int end){
if(begin>end)
return;
else{
int p = patartion(a,begin,end);
Quick(a,begin,p-1);
Quick(a,p+1,end);
}
}
int main()
{
int n;
int x;
printf("输入待查找数组的大小:");
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
if(!judge(a,n))//如果数组无序,则利用快速排序给数组排序
Quick(a,0,n);
//for(int i=0;i<n;i++)
// printf("%d ",a[i]);
printf("输入要查找的元素:");
scanf("%d",&x);
int pos = binary_search(a,0,n,x);
if(pos==-1)
printf("not find!\n");
else
printf("%d\n",pos);
return 0;
}
算法实验-实验一:二分查找法
最新推荐文章于 2021-12-02 09:37:48 发布