phatboislym

binary search algo

Jan 2nd, 2023 (edited)
1,524
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.77 KB | None | 0 0
  1. def binary_search(arr, target):
  2.     # Set the start and end indices
  3.     start = 0
  4.     end = len(arr) - 1
  5.  
  6.     # Keep searching until the start index is greater than the end index
  7.     while start <= end:
  8.         # Calculate the middle index
  9.         mid = (start + end) // 2
  10.  
  11.         # If the middle element is the target value, return its index
  12.         if arr[mid] == target:
  13.             return mid
  14.  
  15.         # If the middle element is less than the target value, search the right half of the array
  16.         elif arr[mid] < target:
  17.             start = mid + 1
  18.  
  19.         # If the middle element is greater than the target value, search the left half of the array
  20.         else:
  21.             end = mid - 1
  22.  
  23.     # If the target value is not found, return -1
  24.     return -1
  25.  
Advertisement
Add Comment
Please, Sign In to add comment