一.数组中的基本操作: 顺序查找元素
任务: 输入关键字key,在数组中找出其位置.
#include <stdio.h>
#define SIZE 10 //定义常量,便于维护;
int main()
{
int d[SIZE] = { 34,43,98,72,12,47,31,1,78 };//数组全部初始化;
int i; //用于循环计数和数组下标的传递;
int key; //进行索引查找的数据;
int index = -1; //保存数组的下标,赋初值便于判断;
printf("Input a key you want to search: "); //提示输入查找数据;
scanf_s("%d", &key);
for (i = 0; i < SIZE; ++i) //循环遍历数组进行查找比较;
{
if (d[i] == key)
{
index = i; //将查到的数组下标赋值给index;
break;
}
}
if (index >= 0) //index跟初始值-1不同,判断是否找到;
{
printf("The index of the key is %d .\n", index);
}
else
{
printf("Not fount.\n");
}
return 0;
}
运行结果:
Input a key you want to search: 72
The index of the key is 3 .
二.体会二分思想
一个小游戏
甲在纸上写一个1000以内的数字,由乙猜
乙每猜一个数,甲需要告诉他大了还是小了
乙采取什么策略,可以用最少的次数猜对数字?(每次都猜中间值)
![](https://i-blog.csdnimg.cn/blog_migrate/6b2e03bbd579f3565677728b925c4609.png)
用二分法查找前提: 数组为有序数列,一次比较,缩减一半的规模
#include <stdio.h>
#define SIZE 10 //定义常量,便于维护;
int main()
{
int d[SIZE] = { 1,3,9,12,32,41,45,62,75,77 }; //数组有序;
int low; //定义查找范围下限;
int high; //定义查找范围上限;
int mid; //范围内的中间值;
int key; //进行索引查找的数据;
int index = -1; //保存数组的下标,赋初值便于判断;
printf("Input a key you want to search: "); //提示输入查找数据;
scanf_s("%d", &key);
low = 0; //与数组第一个元素下标对应;
high = SIZE - 1; //与数组最后一个元素下标对应;
while (low <= high)
{
mid = (low + high) / 2; //确定数组中间值下标;
if (d[mid] == key) //中间值==要查找的值情况,数据找到;
{
index = mid; //mid即为要查找数据的下标值;
break;
}
else if (d[mid] > key) //中间值>查找的值时,证明要找的值在low和mid中间;
{
high = mid - 1; //low不变,将mid-1变为上限high;
}
else
{
low = mid + 1; //否则,high不变,将mid+1变为下限low;`
}
}
if (index >= 0) //用index跟初始值-1是否相同,判断是否找到;
{
printf("The index of the key is %d .\n", index);
}
else
{
printf("Not fount.\n");
}
return 0;
}
可在Visual Studio 2019中,按F11启动单步调试,便于观察和理解