Learning algorithm: dichotomy

Description:

Binary_search function accepts an ordered array element and, if the specified elements contained in the array, this function will return to its position. Find the beginning of the entire array, each inspection the middle of the element, if guess small number, corresponding to the modified low; if guess the big number, and the corresponding modification high.

Code:

. 1  DEF binary_search (List1, Item):
 2      Low = 0
 . 3      High = len (List1) -1
 . 4  
. 5      the while Low <= High:        # long range is not reduced to contain only one element 
. 6          MID = (High + Low) // 2   # check the intermediate element 
. 7          GUESS = List1 [mID]
 . 8          IF GUESS == Item:
 . 9              return mID        # returns the index 
10          IF GUESS> Item:
 . 11              High = -1 mID
 12 is          IF GUESS < Item:
 13 is             low = mid + 1
14             
15     return None
16 
17 my_list = [1,3,5,7,9]
18 
19 print(binary_search(my_list,7))
20 print(binary_search(my_list,3))
21 print(binary_search(my_list,-1))

result:

3
1
None

 

Guess you like

Origin www.cnblogs.com/hqq2019-10/p/11681417.html