#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;
}
c_对分查找
最新推荐文章于 2022-07-05 09:32:10 发布