21xrx.com
2024-04-24 20:06:50 Wednesday
登录
文章检索 我的文章 写文章
C中的线性搜索
2021-07-07 07:06:46 深夜i     --     --
C 线

C 中的线性搜索以查找数组中是否存在数字。 如果它存在,那么它发生在什么位置。 它也称为顺序搜索。 它很简单,工作原理如下:我们将每个元素与要搜索的元素进行比较,直到找到它或列表结束。 线性搜索多次出现并使用函数。

 

C中的线性搜索程序

#include <stdio.h>


int main()
{
  int array[100], search, c, n;

  printf("Enter number of elements in array\n");
  scanf("%d", &n);

  printf("Enter %d integer(s)\n", n);

  for (c = 0; c < n; c++)
    scanf("%d", &array[c]);

  printf("Enter a number to search\n");
  scanf("%d", &search);

  for (c = 0; c < n; c++)
  {
    if (array[c] == search)    /* If required element is found */
    {
      printf("%d is present at location %d.\n", search, c+1);
      break;
    }
  }
  if (c == n)
    printf("%d isn't present in the array.\n", search);

  return 0;
}

 

程序输出:

下载线性搜索程序。

用于二分查找的 C 程序

多次出现的线性搜索 C 程序

在下面的代码中,我们将打印找到所需元素的所有位置以及它在列表中出现的次数。

#include <stdio.h>
 
int main()
{
   int array[100], search, c, n, count = 0;
   
   printf("Enter number of elements in array\n");
   scanf("%d", &n);
   
   printf("Enter %d numbers\n", n);
   
   for (c = 0; c < n; c++)
      scanf("%d", &array[c]);
     
   printf("Enter a number to search\n");
   scanf("%d", &search);
   
   for (c = 0; c < n; c++) {
      if (array[c] == search) {
         printf("%d is present at location %d.\n", search, c+1);
         count++;
      }
   }
   if (count == 0)
      printf("%d isn't present in the array.\n", search);
   else
      printf("%d is present %d times in the array.\n", search, count);
     
   return 0;
}

下载线性搜索多次出现程序。

代码输出:

使用函数进行线性搜索的 C 程序

#include <stdio.h>
 
long linear_search(long [], long, long);
 
int main()
{
   long array[100], search, c, n, position;
 
   printf("Input number of elements in array\n");
   scanf("%ld", &n);
 
   printf("Input %d numbers\n", n);
 
   for (c = 0; c < n; c++)
      scanf("%ld", &array[c]);
 
   printf("Input a number to search\n");
   scanf("%ld", &search);
 
   position = linear_search(array, n, search);
 
   if (position == -1)
      printf("%d isn't present in the array.\n", search);
   else
      printf("%d is present at location %d.\n", search, position+1);
 
   return 0;
}
 
long linear_search(long a[], long n, long find) {
   long c;
 
   for (c = 0 ;c < n ; c++ ) {
      if (a[c] == find)
         return c;
   }
 
   return -1;
}

使用指针的线性搜索功能

long linear_search(long *p, long n, long find) {
  long c;
 
  for (c = 0; c < n; c++) {
    if (*(p+c) == find)
      return c;
  }
 
  return -1;
}

使用该算法搜索元素所需的时间取决于列表的大小。 在最好的情况下,它出现在列表的开头,在最坏的情况下,元素出现在列表的末尾。 它的时间复杂度是 O(n)。

  
  
下一篇: C中的二分搜索

评论区

{{item['qq_nickname']}}
()
回复
回复