#include<stdio.h>
#define MAX 10
int select(int a[],int key,int low,int high)//key:要查找的元素 low:起始位置 high:结束位置
{
if(low<0||high>MAX-1)
{
printf("位置范围错误");
return -1;
}
if(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
return select(a,key,low,mid-1);
else
return select(a,key,mid+1,high);
}
else
{
printf("没有找到");
return -1;
}
}
int main()
{
int low,high,key;
int a[MAX]={1,2,3,4,5,6,7,8,9,10};
printf("请输入要查找的起始下标:");
scanf("%d",&low);
printf("请输入要查找的结束下标:");
scanf("%d",&high);
printf("请输入要查找的值");
scanf("%d",&key);
printf("该数的下标为:%d",select(a,key,low,high));
return 0;
}
递归实现折半查找
最新推荐文章于 2021-12-16 15:00:08 发布