binary-search.py 590 B

123456789101112131415161718192021222324
  1. # Binary search for the target in a sorted array, assume the array has no dups
  2. # Time complexity: O(logn)
  3. # Space complexity: O(1)
  4. import pytest
  5. def test_binary_search():
  6. case1 = [0,1,2,3]
  7. assert binary_search(case1,1) == 1
  8. assert binary_search(case1,0) == 0
  9. assert binary_search(case1, 0.5) == -1
  10. def binary_search(l, target):
  11. left = 0
  12. right = len(l)-1
  13. while right >= left:
  14. m = (right - left )//2
  15. if l[m] == target:
  16. return m
  17. if target < l[m]:
  18. right = m - 1
  19. else:
  20. left = m + 1
  21. return -1