递归与分治2

#include<stdio.h>
/*
递归 实现折半查找
*/

//普通折半查找
int binSearch_Normal(int A[],int n,int e)
{
	int low = 0,high = n-1,mid;
	while(low <= high)
	{
		mid = (low + high) / 2;
		if(A[mid] == e)
			return mid;
		if(e > A[mid])
			low = mid + 1;
		else
			high = mid - 1;
	}
	return -1;
}

//递归折半查找
int binSearch(int A[],int low,int high,int e)
{
	int mid;
	if(low > high) 
		return -1;
	else
	{
		mid = (low + high) / 2;
		if(A[mid] == e)
			return mid;
		else if(e > A[mid])
			return binSearch(A,mid+1,high,e);
		else
			return binSearch(A,low,mid-1,e);
	}
}

int main()
{
	int n,index;
	int A[10] = {2,3,4,5,6,7,8,9,10,13};
	scanf("%d",&n);
	index = binSearch(A,0,9,n);
	if(index==-1)
		printf("can not find\n");
	else
		printf("find,index is %d\n",index);
	return 0;
}

    原文作者:递归与分治算法
    原文地址: https://blog.csdn.net/aasyk2love/article/details/9149135
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞