Python 中的线性搜索

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

线性搜索算法

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

线性搜索的 Python 实现

Python
 pythonCopydef 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)

输出:

 textCopyElement is found at index: 1

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

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: 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