用于数字线性搜索的 C 程序


2022 年 3 月 28 日, Learn eTutorial
1689

什么是线性搜索算法?

C 语言中的线性搜索用于查找元素是否存在于元素列表中。它也称为**顺序搜索**。我们使用**数组概念在 C 语言中输入值列表**。线性搜索算法是 C 编程中使用的简单搜索算法之一。**线性搜索算法的工作方式是,它将搜索元素与给定数组中的每个元素进行比较,直到找到匹配项或数组遍历完毕。**

例如,让我们在数组“**A**”中取一些数字“**1,2,3,4,5**”。如果我们想使用线性搜索搜索数字“**5**”。搜索算法通过将数字与 **a[0]**(即“**1**”)进行比较来开始搜索数字“**5**”,然后它遍历 **2, 3, 4**,最后在 **a[4]**(即“**5**”)处得到结果,找到匹配项,算法完成。

  • 线性搜索的**最佳**情况是当在数组中第一个找到该项时。
  • **最差**情况是搜索元素最后在数组中找到。

C 语言中如何实现线性搜索?

在此线性搜索 C 程序中,在包含头文件库并使用 `for 循环`将所有用户值插入数组后。我们需要用户输入需要使用线性搜索算法搜索的数字。

将该搜索元素分配给变量后,使用“`for 循环`”将数组的每个元素与该变量进行比较,直到找到搜索元素或到达数组末尾,并显示带有适当消息的输出。

算法

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

**步骤 2:** 启动 **main()** 函数以开始执行 C 程序。

**步骤 3:** 初始化将在程序中使用的数组和变量。

**步骤 4:** 使用 `printf` 和 `scanf` 函数接受用户需要的元素数量,并将该整数值存储到变量中。

**步骤 5:** 使用“`for 循环`”接受并将元素添加到数组中。

**步骤 6:** 使用 `for 循环`和 `printf` 显示数组中的元素。

**步骤 7:** 接受用户要搜索的元素并将其保存到变量中。

**步骤 8:** 打开一个从零到项数的 `for 循环`,并为线性搜索的每个元素将其递增一。

**步骤 9:** 使用 if 条件将搜索元素与数组元素进行比较,并在数组中找到该数字时将其标记为“已找到”。

**步骤 10:** 循环检查后,如果“**found = 1**”,则元素已找到,否则打印未找到。

C 语言源代码

                                          #include <stdio.h>

void main() 
{
   int array[10];
   int i, N, keynum, found = 0;                   
 
   printf("Enter the value of N\n");                 /* enters the number of values needed  */
   scanf("%d", & N);
   printf("Enter the elements one by one\n");            /* enter the values into a array and print the numbers */
   for (i = 0; i < N; i++)                 /*entering the elements in to the array */
   {
      scanf("%d", & array[I]);
   }
   printf("Enter the element to be searched\n");         /* enters the search element by the user */
   scanf("%d", & keynum);

   for (i = 0; i < N; i++)        /*using linear search we compare the number with other elements in array */ 
   {
      if (keynum == array[I]) 
      {
         found = 1;
         break;
      }
   }
   if (found == 1)
       printf("SUCCESSFUL SEARCH\n");
   else
       printf("Search is FAILED\n");
} 
                                      

输出

RUN 1

Enter the value of N
5

Enter the elements one by one
23
12
56
43
89

Enter the element to be searched
56
SUCCESSFUL SEARCH

RUN 2

Enter the value of N
3

Enter the elements one by one
456
213
879

Enter the element to be searched
1000

Search is FAILED