Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2675559
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5921
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: C/C++

2014-12-26 20:31:48

#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;
}

阅读(536) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~