折半查找的递归实现和非递归实现(c++)

#include
//折半查找   非递归实现
int BinSearch1(int r[],int n,int k)
{
int mid,low =1,high =n;
while (low <=high)
{
mid =(low + high)/2;
if(kr[mid])low =mid +1;
else return mid;
}
return 0;
}

//折半查找递归实现
int BinSearch2(int r[],int low,int high,int k)
{
int mid;
if (low>high)return 0;
else {
mid =(low+high)/2;
if (kr[mid])return BinSearch2(r,mid+1,high,k);
else return mid;
}
}

int main()
{
int r[10]={0,7,14,18,21,23,29,31,35,38};
int k,i;
printf("元素序列为:\n");
for (i=1;i<10;i++)
printf("%5d",r[i]);
printf("\n请输入要查找的元素值:");
scanf("%d",&k);
if (BinSearch1(r,9,k)==0)
printf("查找失败!\n");
else
printf("非递归方法查找该元素所在位置为:%d\n",BinSearch1(r,9,k));

//调用折半查找递归实现的函数BinSearch2
if (BinSearch2(r,1,9,k)== 0)
printf("查找失败!\n");
else
printf("递归方法查找该元素所在位置为:%d\n",BinSearch2(r,1,9,k));

getchar();getchar();
return 0;
}

 

折半查找的递归实现和非递归实现(c++)_第1张图片

你可能感兴趣的:(算法设计)