#include<stdio.h>
#include<stdlib.h>
int cmp(const void *a,const void *b){
return *(int *)a-*(int *)b;
}
int Search(int *a,int low,int high,int key){
int mid=(low+high)/2;
if(low<=high)
{
if(a[mid]==key)
return mid;
if(a[mid]<key)
return Search(a,low,mid-1,key);
return Search(a,mid+1,high,key);
}
}
int main()
{
int *a;
int n,i,key;
printf("请输入表元素个数\n");
scanf("%d",&n);
a=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
qsort(a,n,sizeof(a[0]),cmp);
printf("从小到大排序如下:\n");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
puts("");
printf("输入您要查找的元素:\n");
scanf("%d",&key);
printf("您要查找的元素在第%d个位置:\n",Search(a,0,n-1,key)+1);
system("pause");
return 0;
}
折半查找的递归实现与qsort
最新推荐文章于 2020-11-24 23:11:57 发布