用递归的方法实现折半查找

#include<stdio.h>
int BinarySearch(int *a,int x,int left,int right);
int main(void)
{

//注:数组必须是有序的

//int a[]={1,2,3,4,5,6,7,8,9,10,12,14,15,18,20};
int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int num,result;
printf("输入要查找的数:");
scanf("%d",&num);
result = BinarySearch(a,num,0,14);
if(result<0)
printf("你要查找的数据不存在!\n");
else
printf("数组里下标为%d的元素值等于%d\n",result,num);
return 0;
}
//自定义一个函数
//数组指针,要查找的数,首元素,末元素
int BinarySearch(int *a,int x,int left,int right)
{
int middle;
if(left<=right)
{

//在这初始化middle的值是为了防止溢出
middle = (left+right)/2;
if(a[middle]==x)
return middle;
else if(a[middle]<x)
left = middle +1;
else if(a[middle]>x)
right = middle -1;
//注意return递归必须是执行的
return BinarySearch(a,x,left,right);
}
return -1;
}

posted @ 2016-10-24 14:26  caocx  阅读(6520)  评论(0编辑  收藏  举报