fork(1) download
  1. def binary_search(arr, target):
  2. low, high = 0, len(arr) - 1
  3. steps = 0 # to see how many iterations happen
  4. while low <= high:
  5. steps += 1
  6. mid = (low + high) // 2
  7. if arr[mid] == target:
  8. print(f"Found in {steps} steps")
  9. return mid
  10. elif arr[mid] < target:
  11. low = mid + 1
  12. else:
  13. high = mid - 1
  14. print(f"Not found in {steps} steps")
  15. return -1
  16.  
  17. # Sorted array
  18. arr = list(range(1, 1000000))
  19. binary_search(arr, 876543)
  20.  
Success #stdin #stdout 0.14s 52140KB
stdin
Standard input is empty
stdout
Found in 18 steps