二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。
通常在查找数组的时候,会发现一个一个查找很浪费资源,因此通过二分查找法实现 。
算法要求:
1.必须采用顺序存储结构。
2.必须按关键字大小有序排列。
首先,假设表中元素是按升序排列,将表中间位置记录的关键字与查找关键字比较,如果两者相等,则查找成功;否则利用中间位置记录将表分成前、后两个子表,如果中间位置记录的关键字大于查找关键字,则进一步查找前一子表,否则进一步查找后一子表。重复以上过程,直到找到满足条件的记录,使查找成功,或直到子表不存在为止,此时查找不成功。
(上面是思维导图)
#include<stdio.h>
#include <windows.h>
//while、do while 、goto、for、递归
void digui(int shang,int xia,int zhong,int num)
{
zhong = (shang + xia) / 2;
if (shang <= xia)
{
if (num == zhong)
{
printf("递归:find.%d\n", zhong);
return;
}
else if (num < zhong)
{
xia = zhong - 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
else
{
shang = zhong + 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
}
return;
}
int main()
{
int a[1024];
for (int i = 0; i<1024; i++) {
a[i] = i;
//printf("%d\n",a[i]);
}
int shang = 0;
int xia = 1023;
int zhong = (shang + xia) / 2;
int num = 102;
while (shang <= xia)//一、while
{
zhong = (shang + xia) / 2;
if (num == zhong)
{
printf("while:find.%d\n", zhong);
break;
}
else if (num < zhong)
{
xia = zhong - 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
else
{
shang = zhong + 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
}
printf("==================\n");
printf("==================\n");
printf("==================\n");
shang = 0;
xia = 1023;
zhong = (shang + xia) / 2;
num = 102;
do {//二、do while
zhong = (shang + xia) / 2;
if (num == zhong)
{
printf("do while:find.%d\n", zhong);
break;
}
else if (num < zhong)
{
xia = zhong - 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
else
{
shang = zhong + 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
} while (xia>=shang);
printf("==================\n");
printf("==================\n");
printf("==================\n");
shang = 0;
xia = 1023;
zhong = (shang + xia) / 2;
num = 988;
AAA://三、goto
zhong = (xia + shang) / 2;
if (num == zhong)
{
printf("goto:find.%d\n", zhong);
goto BBB;
}
else if (num > zhong)
{
shang = zhong + 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
else
{
xia = zhong - 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
if (shang<=xia)
{
goto AAA;
}
BBB:
printf("==================\n");
printf("==================\n");
printf("==================\n");
shang = 0;
xia = 1023;
zhong = (shang + xia) / 2;
num = 288;
for (int i; shang <= xia ;zhong = (shang + xia) / 2)
{
if (num == zhong)
{
printf("for:find.%d\n", zhong);
break;
}
else if (num < zhong)
{
xia = zhong - 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
else
{
shang = zhong + 1;
printf("shang.%d,zhong.%d,xia.%d \n", shang, zhong, xia);
}
}
printf("==================\n");
printf("==================\n");
printf("==================\n");
shang = 0;
xia = 1023;
zhong = (shang + xia) / 2;
num = 288;
digui(shang,xia,zhong,num); //递归
getchar();
getchar();
Sleep(5000);
return 0;
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。