使用线性搜索查找元素的 C 程序


2022年3月27日, Learn eTutorial
1520

为了更好地理解,我们始终建议您学习下面列出的C语言编程基础主题

什么是线性搜索?

在本程序中,我们将讨论元素的线性搜索。为此,我们需要更多地了解数组中元素的线性搜索。线性搜索也称为顺序搜索。从名称本身,我们可以说线性搜索是一种搜索元素的方法。它需要逐一检查所有元素,直到找到所需的元素。

在线性搜索中,它基本上会遍历表中所有记录,只有找到所需结果时才会停止。我们必须将每个元素与要搜索的元素进行比较,直到找到它或数组结束。

该程序的逻辑是导入头文件以使用 C 中的内置函数。首先,将数组 table[20]、i、low、mid、high、key、size 声明为整数数据类型。然后将数组的大小读入变量 size

使用 for 循环 从用户读取数组元素。读取键值并将其保存到变量 key 中。设置 low=0,high=size-1。通过使用带条件“low<=high”的 while 循环,然后计算 mid=low+high/2。检查 key=table[mid] 是否显示搜索成功并退出。如果未找到键,则显示搜索不成功

算法

步骤 1: 包含头文件以使用 C 程序中的内置函数。

步骤 2: 将变量 table[20]、i、low、mid、high、key、size 声明为整数。

步骤 3: 将数组的大小读入变量 size

步骤 4: 使用 for 循环 将数组元素读入 table[i]

步骤 5: 将键值读入变量 key

步骤 6: 设置 low=0,和 high=size-1

步骤 7: 通过使用 while 循环 检查 low<=high,然后分配 mid=low+high/2

步骤 8: 检查 if key==table[mid] 是否显示搜索成功并退出。否则执行步骤 9。

步骤 9: 如果键

步骤 10: 如果未找到键,则显示搜索不成功。

C 语言源代码

                                          #include <stdio.h>

void main() {
  int table[20];
  int i, low, mid, high, key, size;
  printf("Enter the size of an array\n");
  scanf("%d", & size);
  printf("Enter the array elements\n");
  for (i = 0; i < size; i++) {
    scanf("%d", & table[i]);
  }
  printf("Enter the key\n");
  scanf("%d", & key);
  low = 0; /* search begins */
  high = (size - 1);
  while (low <= high) {
    mid = (low + high) / 2;
    if (key == table[mid]) {
      printf("SUCCESSFUL SEARCH\n");
      return;
    }
    if (key < table[mid])
      high = mid - 1;
    else
      low = mid + 1;
  }
  printf("UNSUCCESSFUL SEARCH\n");
} /* End of main() */

                                      

输出

Enter the size of an array
5

Enter the array elements
12
36
45
78
99

Enter the key
45

SUCCESSFUL SEARCH