Advertisement
banovski

Binary search

Nov 10th, 2022 (edited)
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | Source Code | 0 0
  1. array = list(range(1000000))
  2.  
  3. # array.index(2)
  4. # 4 function calls in 0.065 seconds
  5.  
  6. def get_binary_index(array, element):
  7.     l = 0
  8.     r = len(array) - 1
  9.  
  10.     while l <= r:
  11.         m = (l + r) // 2
  12.  
  13.         if array[m] == element:
  14.             return m
  15.  
  16.         if array[m] < element:
  17.             l = m + 1
  18.         else:
  19.             if array[m] > element:
  20.                 r = m - 1
  21.  
  22.     return -1
  23.  
  24. # get_binary_index(array, 2)
  25. # 5 function calls in 0.062 seconds
  26.  
  27. def binary_search(array, number):
  28.     array_length = len(array)
  29.     min_index = 0
  30.     max_index = array_length - 1
  31.     current_index = array_length // 2
  32.  
  33.     while True:
  34.  
  35.         if array[current_index] == number:
  36.             return(current_index)
  37.             break
  38.  
  39.         if array[current_index] > number:
  40.             max_index = current_index
  41.             current_index = (max_index - min_index) // 2
  42.             continue
  43.  
  44.         if array[current_index] < number:
  45.             min_index = current_index
  46.             current_index += (max_index - min_index) // 2 + (max_index - min_index) % 2
  47.  
  48.     else:
  49.         return(-1)
  50.  
  51. # binary_search(array, 2)
  52. # 5 function calls in 0.062 seconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement