- Sequential Lookup
- Two-point Search
- Practice
First, sequential search
Data=[1,3,4,5,6]value=1def 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 (' Find failed ') # Linear_search (Data,value)
Two or two points find
Recursion: (not high efficiency)
Recursion requires an end condition (len (data) <=1), and each recursive problem is reduced in size
Change is the data that is passed in every
#递归实现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 (' Find failed ')
Non-recursive:
Change the direction of the low and high pointers
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 (' Find failed ') print (Bin_search (data,value))
Third, practice
#练习info =[ {"id": 1001, "name": "Zhang San", "Age": $}, {"id": 1002, "name": "John Doe", "Age": [], {"id": 1004, "name": " Harry "," Age ": +}, {" id ": 1007," name ":" Zhao Liu "," 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: #取字典的value with Dic[key] return (Mid, Data[mid]) elif data[mid][' id ']<value: low=mid+1 Else: high=mid-1 Else: return (0,none) #根据返回值判断是否查到这个人while True: id=int (Input (' Please enter the number you want to find (Exit press Q): '). Strip ()) # print (Type (ID) ) If id== ' Q ': break Else: num,info=bin_search (info,id) if info== ' None ': print (' No this person ') Else: print (' info:%s '%info)
The principle of common search algorithm and Python implementation