# Binary search
# Input: Array A by ascending order of the number to be searched num
# Outputs: If found, the position of the element is output, if not searched, the output "to the value No Search"; and outputs a comparison frequency count_compare
. 1 Import Math 2 . 3 DEF binary_search (A, NUM): . 4 . 5 Print ( ' \ array of n inputs is: ' , A) . 6 Print ( ' Number to search as: ' , NUM) . 7 . 8 n = len (A ) # n-array length . 9 low = 0 # low address pointer pointing to a lower 10 high =. 1-n- # high point of the high address pointer . 11 num_location = -1 # position of the element to be searched num_location 12 = count_compare 0 13 is 14 15 the while high - low>. 1 and num_location == -1 : 16 . 17 MID = Math.floor ((low + high) / 2) # MID pointers to low and high central element, floor represents downwardly rounding 18 is . 19 iF a [MID] == NUM: 20 is num_location = MID # if and only if the value to be searched to find, will change the value of num_location 21 is elif a [MID] <= NUM: 22 is Low = MID 23 is the else : 24 High = MID 25 26 is count_compare = count_compare +. 1 27 28 # Print ( 'i-Run search:', count_compare) 29 # Print ( 'MID', MID); Print ( 'Low', Low); Print ( 'High', High) 30 31 is 32 IF High - Low ==. 1: # If the pointer points to two adjacent elements, then the value to search for either one of these two elements, or does not exist 33 is IF a [Low] == NUM: 34 is = num_location Low 35 elif A [High] == NUM: 36 num_location = High 37 [ count_compare count_compare +. 1 = 38 is #Note: In rare cases, if the last two numbers are equal, and both the number to be searched, if this is judged by the statement, num_location becomes high, i.e. only the position of the output element back 39 40 41 is if == -1 num_location: # Description not searched value to search 42 is Print ( ' \ n-value is not the search ' ) 43 is Print ( ' the number of comparisons is: ' , count_compare) 44 is the else : 45 Print ( ' \ n-in the array location: ' , num_location +. 1 ) 46 is Print ( ' the number of comparisons is: ' , count_compare)
Function call
1 A = [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999] 2 num = 110 3 binary_search(A,num)
operation result
Input array is: [-39, -22, -1, 5, 12, 21, 33, 56, 56, 76, 92, 92, 110, 999 ] Number to search as follows: 110 location in the array: 13 the number of comparisons is: 4