The principle and python implementation of common search algorithms

  • Sequential search
  • binary search
  • practise

1. Sequential search

data=[1,3,4,5,6]
value=1
def linear_search(data,value):
    flag=False
    for i in range(0,len(data)):
        if data[i]==value:
            # return i
            flag=True
            print('Found, at %s position '%i)
    if not flag:
        print('Search failed')
# linear_search(data,value)

Two, binary search

Recursion: (inefficient)

The recursion needs to have an end condition (len(data)<=1), and the problem size of each recursion is reduced

What changes is the data that is passed in each time

# recursive implementation
def bin_search2(data,value):
    mid=len(data)/2
    if len(data)>1:
        if value>data[mid]:
            bin_search2(data[mid+1:],value)
        elif value<data[mid]:
            bin_search2(data[0:mid-1],value)
        else:
            return mid
    else:
        if data[0]==value:
            return 0
        else:
            print('Search failed')

Non-recursive:

What changes is the low and high pointers point to

def bin_search(data,value):
     flag=False
     low=0
     high=len(data)-1
     while low<=high:
         mid=(low+high)//2
         if value>data[mid]:
             low=mid+1
         elif value<data[mid]:
             high=mid-1
         else:
             flag=True
             return mid
     if not flag:
         print('Search failed')
print(bin_search(data,value))

3. Practice

#practise
info=[
    {"id":1001, "name":"张三", "age":20},
    {"id":1002, "name":"李四", "age":25},
    {"id":1004, "name":"王五", "age":23},
    {"id":1007, "name":"赵六", "age":33}
]
def bin_search(data,value):
    low=0
    high=len(data)-1
    while low<=high:
        mid=(low+high)//2
        if data[mid]['id']==value:# Take the value of the dictionary with dic[key]
            return (mid,data[mid])
        elif data[mid]['id']<value:
            low=mid+1
        else:
            high=mid-1
    else:
        return (0,None)#According to the return value to determine whether the person is found

while True:
    id=int(input('Please enter the student ID to be searched (please press Q to exit):').strip())
    # print(type(id))
    if id=='q':
        break
    else:
        num,info=bin_search(info,id)
        if info=='None':
            print('No such person found')
        else:
            print('info:%s'%info)

  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076756&siteId=291194637