Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def binary_search(arr, target):
- # Set the start and end indices
- start = 0
- end = len(arr) - 1
- # Keep searching until the start index is greater than the end index
- while start <= end:
- # Calculate the middle index
- mid = (start + end) // 2
- # If the middle element is the target value, return its index
- if arr[mid] == target:
- return mid
- # If the middle element is less than the target value, search the right half of the array
- elif arr[mid] < target:
- start = mid + 1
- # If the middle element is greater than the target value, search the left half of the array
- else:
- end = mid - 1
- # If the target value is not found, return -1
- return -1
Advertisement
Add Comment
Please, Sign In to add comment