How to implement binary search in Python? #6
Answered
by
deathlegionteamlk
deathlegionteamlk
asked this question in
Q&A
-
|
I need help implementing an efficient binary search algorithm. What is the best approach? |
Beta Was this translation helpful? Give feedback.
Answered by
deathlegionteamlk
Jun 4, 2026
Replies: 1 comment
-
|
Here is a great binary search implementation in Python: def binary_search(arr, target):
left, right = 0, len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1This runs in O(log n) time. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
deathlegionteamlk
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a great binary search implementation in Python:
This runs in O(log n) time.