Advertisement
kai-rocket

Binary Search

Mar 26th, 2021
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. class Solution:
  2.     def search(self, nums: List[int], target: int) -> int:
  3.        
  4.         # Initialise our bounds to start and end of nums array
  5.         left_index = 0
  6.         right_index = len(nums) - 1
  7.        
  8.         # Loop while we have not yet searched all numbers
  9.         while left_index <= right_index:
  10.            
  11.             # Search the middle number of our range
  12.             mid_index = (left_index + right_index) // 2
  13.             mid_num = nums[mid_index]
  14.            
  15.             # If target found, return mid_index
  16.             if mid_num == target:
  17.                 return mid_index
  18.            
  19.             # If target is greater than mid number
  20.             if mid_num < target:
  21.                 left_index = mid_index + 1
  22.                
  23.             # If target is less than mid number
  24.             else:
  25.                 right_index = mid_index - 1
  26.        
  27.         # If target not found, return -1
  28.         return -1
  29.                
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement