Dichotomy is a fast-finding method, with a low time complexity and simple logic, which is generally divided by 2 divided by 2 ...
For example, to find the location of a keyword key in an ordered list, first confirm the list's median mid, which is divided into three scenarios:
If LIST[MID] < key, indicate that key is on the right of the median;
If List[mid] > key, indicate that key is on the left of the median;
If list[mid] = key, indicates that key is in the middle of the median;
The range shrinks by half each time, writing a while loop to know until it is found.
Binary lookup is very fast and very common, but the only requirement is that the array is ordered
The code is as follows
1 #!/usr/bin/python2.72 #-*-coding:utf-8-*-3 4 defBinarySearch (Lista, key):5 #record the highest and lowest bits of an array6Min =07max = Len (lista)-18 9 ifKeyinchlista:Ten #build a dead loop until you find the key One whileTrue: A #get the median number -Mid = (min + max)/2 - #key to the left of the array the ifLista[mid] >Key: -max = Mid-1 - #key to the right of the array - elifLista[mid] <Key: +Min = mid + 1 - #key in the middle of the array + elifLista[mid] = =Key: A PrintSTR (KEY) +"in the array, the first"+ STR (MID) +"a location" at returnLista[mid] - Else: - Print("no such number!") - - - if __name__=="__main__": inarr = [1, 6, 9, 15, 26, 38, 49, 57, 63, 77, 81, 93] - whileTrue: toKey = input ("Please enter the number you want to find:") + ifKey = =" ": - Print("Thanks for using! ") the Break * Else: $BinarySearch (lista, int (key))
Python uses a binary method to find the specified element in a sequential table