#include
typedef unsigned char BYTE ;
typedef unsigned int U32;
U32 BinarySearch(BYTE * bpin, U32 ulen, BYTE dest);
/*
int main()
{
#define NUM 10
BYTE array[NUM] = {0,1,2,3,4,5,6,7,8,9};
BYTE foo, var, temp;
for(foo = 0; foo < NUM -1; ++foo )
for(var = 0; var < NUM - foo -1; ++var)
{
if(array[var] < array[var + 1])
{
temp = array[var];
array[var] = array[var + 1];
array[var + 1] = temp;
}
}
for(foo = 0; foo < NUM ; ++foo)
printf("The data %d is %d\n",foo, array[foo]);
return 0;
}
*/
int main()
{
#define NUM 10
BYTE array[NUM] = {0,1,2,3,4,5,6,7,8,9};
BYTE foo, var, temp;
U32 receive;
for(foo = 0; foo < NUM -1; ++foo )
for(var = foo; var <= NUM - 1; ++var)
{
if(array[foo] < array[var])
{
temp = array[foo];
array[foo] = array[var];
array[var] = temp;
}
}
for(foo = 0; foo < NUM ; ++foo)
printf("The data %d is %d\n",foo, array[foo]);
receive = BinarySearch(array, NUM, 2);
printf("The return is %d\n", receive);
return 0;
}
#define NOtFound 0;
U32 BinarySearch(BYTE * bpin, U32 ulen, BYTE dest)
{
U32 low, high;
low = 0;
high = ulen;
while(low < high)
{
if(bpin[(low + high) / 2] > dest )
{
low = (low + high) / 2 + 1;
}
if(bpin[(low + high) / 2] < dest)
{
high = (low + high) / 2 + 1;
}
if(bpin[(low + high) / 2] == dest)
return (low + high) / 2;
}
return NOtFound;
}
//改进型二分查找算法
#define NOtFound 0;
U32 BinarySearch(BYTE * bpin, U32 ulen, BYTE dest)
{
U32 low, high, mid;
low = 0;
high = ulen;
while(low < high)
{
mid = (low + high) / 2;
if(bpin[mid] > dest )
{
low = mid + 1;
}
if(bpin[mid] < dest)
{
high = mid + 1;
}
if(bpin[mid] == dest)
return mid;
}
return NOtFound;
}
阅读(539) | 评论(0) | 转发(0) |