分别使用递归和非递归实现二分查找算法

#include<stdio.h>

int BinarySearch(int array[],int len,int findData)
{
   if(array==NULL||len<=0)
	   return -1;
   int start=0;
   int end=len-1;
   while(start<=end)
   {
	   int mid=start+(end-start)/2;
	   if(findData==array[mid])
		   return mid;
	   else if(findData<array[mid])
		   end=mid-1;
	   else
		   start=mid+1;
   }
   return -1;
}

//递归算法
int BinarySearchRecursion(int array[],int findData,int start,int end)
{
	if(start>end)
		return -1;
	int mid=start+(end-start)/2;
	if(array[mid]==findData)
		return mid;
	else if(findData<array[mid])
		return BinarySearchRecursion(array,findData,start,mid-1);
	else
       	return BinarySearchRecursion(array,findData,start,mid-1);
}

int BinarySearchRecursion(int array[],int len,int findData)
{
	if(array==NULL||len<=0)
		return -1;
	return BinarySearchRecursion(array,findData,0,len);
}
int main()
{
	int a[]={1,2,3,4,5,6,7,8};
	int len=sizeof(a)/sizeof(a[0]);
	int index=BinarySearch(a,len,4);
	int index2=BinarySearchRecursion(a,len,9);
	printf("%d\n%d\n",index,index2);
	return 0;
}

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