DSA — Binary Search
What is Binary Search?
Efficiently finds an item in a sorted array by repeatedly dividing the search interval.
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
Recursive Version
def binary_search_recursive(arr, target, left=0, right=None):
if right is None:
right = len(arr) - 1
if left > right:
return -1
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search_recursive(arr, target, mid + 1, right)
else:
return binary_search_recursive(arr, target, left, mid - 1)
Time Complexity
| Case | Complexity |
|---|---|
| Best | O(1) |
| Average | O(log n) |
| Worst | O(log n) |
When to Use
- Sorted data
- Large datasets
- Frequent searches
Mini Practice
- Implement binary search
- Find first/last occurrence
- Search in rotated array
- Find ceiling/floor
Up Next
Continue with Bubble Sort — simple sorting algorithm.
Related Topics
Frequently Asked Questions about Binary Search
What is Binary Search in DSA?
Binary Search is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Binary Search?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Binary Search.
Why is Binary Search important in DSA?
Binary Search is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.