Home > Article > Backend Development > Detailed explanation of linear search algorithm implemented in Python
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.
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.
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
Set k=1 and find the corresponding value from the array.
1. Starting from the first element, compare K with each element X
2. If x==k return the index
3. The algorithm ends. If there is no match, "Not Found" is returned
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!