Home  >  Article  >  Backend Development  >  Detailed explanation of linear search algorithm implemented in Python

Detailed explanation of linear search algorithm implemented in Python

王林
王林forward
2024-01-22 23:27:171268browse

Linear search is the simplest search algorithm. It starts from the beginning of the data set and checks each item of data until a match is found. Once the target is found, the search ends.

Disadvantages of linear search algorithm

It should be noted that although the linear search algorithm is simple, it is not suitable for large data. Since the algorithm compares each data one by one, the more data, The longer it takes.

Advantages of linear search algorithm

1. The data set does not have to be ordered and does not require structured data

2. It is not affected by insertions and deletions. Since the linear search does not call the list to be sorted, the added elements can be inserted and deleted

3. The smaller the amount of data, the higher the efficiency of the linear search algorithm

Linear search algorithm graphic example

Set k=1 and find the corresponding value from the array.

详解线性搜索算法 Python实现线性搜索算法

1. Starting from the first element, compare K with each element X

详解线性搜索算法 Python实现线性搜索算法

2. If x==k return the index

详解线性搜索算法 Python实现线性搜索算法

3. The algorithm ends. If there is no match, "Not Found" is returned

Python implements linear search algorithm

def linearSearch(array,n,x):
    for i in range(0,n):
        if(array<i>==x):
            return i
    return-1

array=[2,4,0,1,9]
x=1
n=len(array)
result=linearSearch(array,n,x)
if(result==-1):
    print("未找到")
else:
    print("值:",result)

The above is the detailed content of Detailed explanation of linear search algorithm implemented in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:163.com. If there is any infringement, please contact admin@php.cn delete