Binary Search is one of the most fundamental and efficient searching algorithms in Data Structures and Algorithms (DSA). It is widely used in real-life systems such as databases, searching in dictionaries, and libraries like bisect in Python or binary_search in C++ STL.
๐ What is Binary Search?
Binary Search is a divide and conquer algorithm used to find the position of a target element in a sorted array.
Instead of scanning each element (like Linear Search), Binary Search divides the array into halves and eliminates one half at each step.
โ Key Points
- Works only on sorted arrays/lists.
- Time Complexity: O(log n).
- Space Complexity: O(1) (iterative) or O(log n) (recursive due to call stack).
- Faster than Linear Search O(n) when dealing with large datasets.
โก Intuition (How to Think?)
Imagine you are searching for a word in a dictionary:
- You donโt start from the first word.
- You open the dictionary in the middle.
- If the word you want comes before the opened word โ search in the left half.
- If it comes after โ search in the right half.
- Repeat until found or not found.
Thatโs exactly how Binary Search works!
๐งฎ Algorithm Steps
- Start with two pointers:
low = 0(start index)high = n-1(end index)
- Find the middle index:
mid = (low + high) / 2 - Compare:
- If
arr[mid] == targetโ element found. - If
arr[mid] > targetโ search in the left half (high = mid - 1). - If
arr[mid] < targetโ search in the right half (low = mid + 1).
- If
- Repeat until
low <= high.
๐ป Iterative Implementation (in PHP)
<?php
function binarySearch($arr, $target) {
$low = 0;
$high = count($arr) - 1;
while ($low <= $high) {
$mid = intdiv($low + $high, 2);
if ($arr[$mid] == $target) {
return $mid; // Element found
} elseif ($arr[$mid] < $target) {
$low = $mid + 1; // Search right
} else {
$high = $mid - 1; // Search left
}
}
return -1; // Element not found
}
// Example usage
$arr = [2, 4, 6, 10, 15, 20, 25];
$target = 15;
$result = binarySearch($arr, $target);
echo ($result != -1) ? "Element found at index $result" : "Element not found";
?>
๐ป Recursive Implementation
<?php
function binarySearchRecursive($arr, $low, $high, $target) {
if ($low > $high) {
return -1; // Not found
}
$mid = intdiv($low + $high, 2);
if ($arr[$mid] == $target) {
return $mid;
} elseif ($arr[$mid] < $target) {
return binarySearchRecursive($arr, $mid + 1, $high, $target);
} else {
return binarySearchRecursive($arr, $low, $mid - 1, $target);
}
}
// Example usage
$arr = [1, 3, 5, 7, 9, 11];
$target = 7;
$result = binarySearchRecursive($arr, 0, count($arr)-1, $target);
echo ($result != -1) ? "Element found at index $result" : "Element not found";
?>
โฑ Complexity Analysis
- Best Case: O(1) โ when the middle element is the target.
- Average Case: O(log n).
- Worst Case: O(log n).
Example: For an array of size n = 1,000,000, Binary Search will take at most logโ(1,000,000) โ 20 steps.
๐ Applications of Binary Search
- Searching in sorted arrays.
- Efficiently finding elements in large datasets.
- In libraries like C++ STL (
binary_search). - Problems like:
- Finding square root of a number.
- Searching in rotated sorted arrays.
- Peak element finding.
- Allocating resources (e.g., minimum number of pages allocation problem).
Why is Binary Search faster than Linear Search?
Linear Search: O(n) โ checks one element at a time.
Binary Search: O(log n) โ eliminates half of the elements in each step.
๐ For large datasets, Binary Search is significantly faster.
Binary Search: O(log n) โ eliminates half of the elements in each step.
๐ For large datasets, Binary Search is significantly faster.
What are the prerequisites for using Binary Search?
The array must be sorted (ascending or descending).
Random access must be possible (works on arrays, not linked lists).
Random access must be possible (works on arrays, not linked lists).
What is the time complexity of Binary Search?
Best Case: O(1) โ element at middle.
Worst Case / Average Case: O(log n).
Worst Case / Average Case: O(log n).
What is the space complexity of Binary Search?
Iterative Binary Search: O(1).
Recursive Binary Search: O(log n) (due to recursive call stack).
Recursive Binary Search: O(log n) (due to recursive call stack).
Can Binary Search be used on Linked Lists?
Not efficiently.
Accessing the middle element in a linked list takes O(n).
So, total complexity becomes O(n log n) โ not efficient.
๐ Binary Search works best with arrays or random-access structures.
Accessing the middle element in a linked list takes O(n).
So, total complexity becomes O(n log n) โ not efficient.
๐ Binary Search works best with arrays or random-access structures.
What are the variations of Binary Search?
First Occurrence of an element.
Last Occurrence of an element.
Count of Occurrences.
Lower Bound / Upper Bound (smallest/largest index where element can be placed).
Search in Rotated Sorted Array.
Binary Search on Answer (used in problems like minimum capacity, allocation, etc.).
Last Occurrence of an element.
Count of Occurrences.
Lower Bound / Upper Bound (smallest/largest index where element can be placed).
Search in Rotated Sorted Array.
Binary Search on Answer (used in problems like minimum capacity, allocation, etc.).
Common pitfalls in Binary Search?
Infinite loop if mid calculation or condition is wrong.
Integer overflow in (low + high) / 2.
Correct way: mid = low + (high – low) / .
Forgetting to update
Integer overflow in (low + high) / 2.
Correct way: mid = low + (high – low) / .
Forgetting to update
low and high properly.How many comparisons does Binary Search make in the worst case?
At most โlogโ(n)โ + 1 comparisons.
Where is Binary Search used in real life?
Search engines (dictionary lookup).
Databases (index searching).
Libraries (
Competitive programming (range-based problems).
Databases (index searching).
Libraries (
bisect in Python, binary_search in C++ STL).Competitive programming (range-based problems).
What if the array is sorted in descending order?
Just reverse the comparison logic:
If
If
If
arr[mid] > target โ search right side.If
arr[mid] < target โ search left side.