Interview essential algorithm | idea and implementation of sequential search (Python)

lookup

​ In principle , The search algorithm is simple , Its core is to find out whether an element exists from an array , Return if present True, Returns if it does not exist False.

In order to find

​ The data items stored in a set such as a list have a linear or sequential relationship with each other , The position of the data item is its subscript , Because subscripts are ordered , So you can access... Sequentially , Therefore, sequential search can be carried out .

The order of the unordered list

​ The idea of sequential search is to traverse from beginning to end to find whether there are elements to be found in the list , When the list we are looking for has no size order, we can only traverse the whole list .

 Insert picture description here

​ The code is implemented as follows :

def seqSearch(alist, item):
pos = 0
found = False
while pos < len(alist) and not found:
if alist[pos] == item:
found = True
else:
pos += 1
# found = false found = True
return found
seqSearch([2, 6, 4, 2, 6, 7], 8)

Find in the order of an ordered list

​ The main difference between an ordered list and an unordered list is the stop condition , Because of the order of the list , So when we find that the element in the list is larger than the element to be found, we can stop looking down .

 Insert picture description here

​ The code is implemented as follows :

def seqSearch(alist, item):
pos = 0
found = False
# Add a stop judge , Current number is greater than item Stop 
stop = False
while pos < len(alist) and not found and not stop:
if alist[pos] == item:
found = True
else:
if alist[pos] > item:
stop = True
else:
pos += 1
return found
seqSearch([2, 3, 4, 5, 6], 9)
Please bring the original link to reprint ,thank
Similar articles