了解线性搜索

    在本教程中,您将学习线性搜索。此外,您还将找到线性搜索C语言的示例。
    线性搜索是最简单的搜索算法,可以按顺序搜索列表中的元素。我们从一端开始检查每个元素,直到找到所需的元素为止。

线性搜索如何工作?

    按照以下步骤在下面的列表中搜索元素k=1。
在这里插入图片描述

  1. 从第一个元素开始,将k与元素x逐一比较。
    在这里插入图片描述
  2. 如果x == k,返回索引。
    在这里插入图片描述
  3. 否则,返回not found。
线性搜索算法伪代码
LinearSearch(array, key)
  for each item in the array
    if item == value
      return its index
C示例
// Linear Search in C

#include <stdio.h>

int search(int array[], int n, int x) {
  
  // Going through array sequencially
  for (int i = 0; i < n; i++)
    if (array[i] == x)
      return i;
  return -1;
}

int main() {
  int array[] = {2, 4, 0, 1, 9};
  int x = 1;
  int n = sizeof(array) / sizeof(array[0]);

  int result = search(array, n, x);

  (result == -1) ? printf("Element not found") : printf("Element found at index: %d", result);
}
线性搜索的复杂度

    时间复杂度:O(n)
    空间复杂度:O(1)

线性搜索的应用

    用于较小数组(<100项)中的搜索操作。

参考文档

[1]Parewa Labs Pvt. Ltd.Linear Search[EB/OL].https://www.programiz.com/dsa/linear-search,2020-01-01.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值