Advertisement
Valeria_Fadeeva

bynary_search python

Aug 1st, 2022 (edited)
946
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. import timeit
  2. import math
  3.  
  4.  
  5. def binary_search(arr, item):
  6.     low = 0
  7.     high = len(arr)-1
  8.  
  9.     while low <= high:
  10.         mid = math.floor((low + high) / 2)
  11.         value = arr[mid]
  12.  
  13.         if value == item:
  14.             return mid
  15.  
  16.         elif value > item:
  17.             high = mid - 1
  18.  
  19.         else:
  20.             low = mid + 1
  21.  
  22.     return None
  23.  
  24.  
  25. max_item_count = 1_000_000_000
  26. arr = [i for i in range(max_item_count)]
  27.  
  28. item = 5
  29.  
  30. t1 = timeit.timeit('binary_search(arr, item)', number=1, globals=globals())
  31. print(f'{t1}')
  32.  
  33.  
  34. time python3 ./binary_search.py
  35. 0.00040091900154948235
  36. 27.4 GB RAM USED
  37.  
  38. real    7m39,021s
  39. user    0m35,848s
  40. sys     7m1,035s
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement