使用二分法查找数组中的元素

上次写了几篇排序的博客,今天写一下查找,而二分法是最基本的查找算法,也是非常重要的查找算法,为了便于理解二分法,我将使用一个具体的程序实现二分查找的应用

使用二分法查找数组中的素

待查找的数组:

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时



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值