上次写了几篇排序的博客,今天写一下查找,而二分法是最基本的查找算法,也是非常重要的查找算法,为了便于理解二分法,我将使用一个具体的程序实现二分查找的应用
使用二分法查找数组中的素
待查找的数组:
|
2 |
4 |
6 |
8 |
10 |
12 |
14 |
16 |
18 |
20 |
实现算法:
定义几个变量num, tou , zhong, wei,
初始化时 tou = 0 wei = 9 zhong = 4 num = 16
其中num是需要查找的数据
第一步:
a[zhong] < num
tou = zhong + 1 = 5
zhong = (tou + wei) / 2 = 7
因为 num == a[zhong]所以找到了,所以16是数组中的第7个数字
程序代码:
#include <stdio.h>
#include <stdlib.h>
#define size 10//标示数组中数字的个数
//向数组中输入数字
void Input(int *a, int len);
//输出数组中的数字
void Output(int *a, int len);
//查找数组中的数字
void Search(int *a, int len);
void main()
{
int a[size];
Input(a,size);
Output(a,size);
Search(a,size);
system("pause");
}
//向数组中输入数字
void Input(int *a, int len)
{
for(int i=0; i<len; i++)
{
a[i] = 2*(i+1);
}
}
//输出数组中的数字
void Output(int *a, int len)
{
for(int i=0; i<len; i++)
{
printf("%d ",a[i]);
}
printf("\n");
}
//查找数组中的数字
void Search(int *a, int len)
{
int num;
printf("请输入一个待查找的数字:");
scanf("%d",&num);
int tou = 0;
int wei = size - 1;
int zhong = (tou+wei)/2;
while(tou<wei && num != a[zhong])
{
if(a[zhong] > num)
{
wei = zhong - 1;
}
else if(a[zhong] < num)
{
tou = zhong + 1;
}
zhong= (tou + wei)/2;
}
if(num != a[zhong])
{
printf("没找到你需要查找的数字!\n");
}
else
{
printf("找到了,%d在数组中的第%d项!\n", a[zhong], zhong);
}
}执行结果:当num = 16时
本文详细介绍了二分查找算法的基本原理及其应用,并通过一个具体的程序实例来演示如何使用二分法在有序数组中查找特定元素。该算法适用于已排序的数据集,能够高效地定位目标值。
1315

被折叠的 条评论
为什么被折叠?



