binary_search.py 447 B

1234567891011121314151617181920212223
  1. # Time complexity: O(logn)
  2. # Space complexity: O(1)
  3. import pytest
  4. def test_binary_search():
  5. case1 = [0,1,2,3]
  6. assert binary_search(case1,1) == 1
  7. def binary_search(l, target):
  8. left = 0
  9. right = len(l)-1
  10. while right > left:
  11. m = (right - left )//2
  12. print(m)
  13. if l[m] == target:
  14. return m
  15. elif target < l[m]:
  16. right = m - 1
  17. else:
  18. left = m + 1
  19. return 0