Python 中的线性搜索

Harshit Jindal 2023年1月30日
  1. 线性搜索算法
  2. 线性搜索的 Python 实现
Python 中的线性搜索
注意
如果你想详细了解线性搜索,那么可以参考线性搜索算法一文。

线性搜索算法

假设我们有一个未排序的数组 A[],包含 n 个元素,我们想找到一个元素-X

  • 使用 for 循环从最左边的元素开始遍历数组中的所有元素,并执行以下操作。
    • 如果 A[i] 的值与 X 匹配,则返回索引 i。(如果有多个元素与 X 匹配,则不返回索引 i,而是打印所有索引或将所有索引存储在一个数组中并返回该数组。)
    • 否则继续下一个元素。
    • 如果你在数组的最后一个元素,退出 for 循环。
  • 如果没有一个元素匹配,那么返回 -1

线性搜索的 Python 实现

def linearsearch(arr, n, x):

    for i in range(0, n):
        if arr[i] == x:
            return i
    return -1


arr = [1, 2, 3, 4, 5]
x = 1
n = len(arr)
position = linearsearch(arr, n, x)
if position == -1:
    print("Element not found !!!")
else:
    print("Element is present at index", position)

输出:

Element is found at index: 1

上述算法的时间复杂度为 O(n)

作者: Harshit Jindal
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn

相关文章 - Python Algorithm