Pesquisa Linear em Python

  1. Algoritmo de pesquisa linear
  2. Implementação de Python de pesquisa linear
Pesquisa Linear em Python
Nota
Se você quiser entender a pesquisa linear em detalhes, consulte o artigo Algoritmo de pesquisa linear.

Algoritmo de pesquisa linear

Vamos supor que temos um array não classificado A[] contendo n elementos, e queremos encontrar um elemento - X.

Implementação de Python de pesquisa linear

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)

Resultado:

 textCopyElement is found at index: 1

A complexidade de tempo do algoritmo acima é O(n).

Está gostando dos nossos tutoriais? Inscreva-se no DelftStack no YouTube para nos apoiar na criação de mais vídeos tutoriais de alta qualidade. Inscrever-se
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

Artigo relacionado - Python Algorithm