Last active
          November 16, 2022 05:42 
        
      - 
      
- 
        Save beyonddream/c73f6f57b1d10172dd08c47fce8e6540 to your computer and use it in GitHub Desktop. 
    binary search in python
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/env python3 | |
| from typing import List | |
| def binary_search(arr: List[int], target: int) -> int: | |
| """ | |
| >>> arr = [3, 6, 12, 18] | |
| >>> target = 12 | |
| >>> binary_search(arr, target) | |
| """ | |
| low, high = 0, len(arr) - 1 | |
| while low <= high: | |
| mid = low + (high - low) // 2 | |
| if arr[mid] == target: | |
| return mid | |
| elif arr[mid] < target: | |
| low = mid + 1 | |
| else: | |
| high = mid - 1 | |
| return -1 | |
| if __name__ == '__main__': | |
| import doctest | |
| doctest.testmod() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment