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

题目:分别用递归和非递归实现有序数组的二分查找算法

 1.递归 C代码实现:

#include <stdio.h>
int binarySort(int a[],int start ,int end, int key)
{
	if(a==NULL || end <0)   //切记,对于数组,操作之前的第一步一定是判断该数组是否存在
		return -1;
	if(start > end)
		return -1;
	int mid = (start+end)/2;
	if(key==a[mid])
		return mid;
    if(key<a[mid])
		return binarySort(a,start,mid-1,key);
	if(key>a[mid])
		return binarySort(a,mid+1,end,key);
	else 
		return -1;
}

int main()
{
	int a[]={1,2,3,4,5,6,7,8,9,10};
	int len = sizeof(a)/sizeof(a[0]);
	int key = 8;
	int res = binarySort(a,0,len-1,key);
	if (res!=-1)
		printf("key is in the array a ,the index is %d ",res);
	else
		printf("key isn't in the array a!");
	return 0;
 } 

 2.非递归C代码实现:

#include <stdio.h>
int binarySort(int a[],int len,int key)
{
	if(a==NULL ||len<=0)     
		return -1;
	int  low = 0;
	int high = len-1;
	while(low <= high)
	{
		int mid = (low+high)/2; 
		if (key==a[mid])
			return mid;
		if(key>a[mid])
			low = mid +1;
		if(key<a[mid])
			high = mid - 1;
			
	}
	return -1;
}
int main()
{
	int a[]={1,2,3,4,5,6,7,8,9,10};
	int len = sizeof(a)/sizeof(a[0]);
	int key =5;
	int res = binarySort(a,len,key);
	printf("%d ",res);
	return 0;
 } 

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