c_对分查找

本文介绍了一种经典的二分查找算法及其递归实现方式。通过示例代码展示了如何在一个有序数组中查找特定元素的位置,包括非找到和错误情况的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdio.h"

typedef int ElementType;

enum{
	NotFind = -2,
	Error = -1,
};

int main()
{
	ElementType a[]={0,1,2,3,4,6,7,8,9,10};
	int size = sizeof(a)/sizeof(a[0]);

	int iRet = BinarySearch(a, 6, size);
	printf("search 6 ,pos: %d\n",iRet);
	iRet = BinarySearch(a, -2, size);
	printf("search -2 ,pos: %d\n",iRet);
	iRet = BinarySearchRecursion(a, 6, 0, size);
	printf("recursion search 6 ,pos: %d\n",iRet);
	iRet = BinarySearch(a, -2, 0, size);
	printf("recursion search -2 ,pos: %d\n",iRet);
	iRet = BinarySearchRecursion(a, 5, 0, size);
	printf("recursion search 5 ,pos: %d\n",iRet);
	return iRet;
}

int BinarySearchRecursion(const ElementType *a, ElementType x, int Low, int High)
{
	ElementType Mid = (Low+High)/2;

	if(Low == High)
	{
		return Error;
	}
	if(*(a+Mid) < x)
	{
		return BinarySearchRecursion(a,x,++Mid,High);
	}
	else if(*(a+Mid) > x)
	{
		return BinarySearchRecursion(a,x,Low,--Mid);
	}
	return Mid;
}
int BinarySearch(const ElementType *a, ElementType x, int size)
{
	ElementType Low,Mid,High;
	Low = 0;
	High = size - 1;

	if(x > *(a+High) || x < *(a+Low))
	{
		printf("High:%d,Low:%d---->\n", *(a+High), *(a+Low));
		return Error;
	}
	while(Low <= High)
	{
		Mid = (Low+High)/2;
		if(*(a+Mid) < x)
		{
			Low = ++Mid;
		}
		else if(*(a+Mid) > x)
		{
			High = --Mid;
		}
		else
		{
			return Mid;
		}
	}
	return NotFind;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值