关闭

c_对分查找

543人阅读 评论(0) 收藏 举报
#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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32406次
    • 积分:796
    • 等级:
    • 排名:千里之外
    • 原创:49篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论