← Back to Home
Binary Search
An efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item.
Visualization
Step 1 / 10
Speed:
Details
Analogy
This is like looking for a name in a phone book. You open to the middle. If the name you're looking for comes alphabetically before the names on that page, you know to focus on the first half. You repeat this, halving your search area each time, until you pinpoint the name.
Purpose
To quickly find the position of a target value within a sorted array.
Use Cases
Extremely common in programming. Used in search engines, database indexing, and any application that requires fast lookups on large, sorted datasets.
Algorithm Steps
Line 1
1
left = 0, right = n-1
2
while left <= right:
3
mid = (left + right) / 2
4
if arr[mid] == target:
5
return mid
6
else if arr[mid] < target:
7
left = mid + 1
8
else:
9
right = mid - 1
10
return -1 (not found)
Current
Executed
Pending
Explanation
What's Happening?
Step 1/10
Start search for target 17 in the full range [0, 9].
Updates with each step • Clickfor full view
Code Implementation
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 -1