Binary Search in Data Structures and Algorithms
Binary Search is an efficient searching algorithm used to find a target element in a sorted array or collection. Instead of checking every element one by one, it repeatedly divides the search range into two halves. By eliminating half of the remaining elements after each comparison, Binary Search can find an element in O(log n) time.
1. What is Binary Search?
Binary Search is a searching technique based on the divide and conquer approach. It works by comparing the target element with the middle element of a sorted array.
Depending on the comparison, the algorithm decides whether to continue searching in the left half or the right half of the array.
- If the middle element equals the target, the element is found.
- If the target is smaller than the middle element, search the left half.
- If the target is greater than the middle element, search the right half.
This process continues until the target is found or the search range becomes empty.
2. Understanding Binary Search with an Example
Consider the following sorted array:
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90]
Suppose we want to search for:
target = 70
The first middle index is calculated using:
mid = (low + high) / 2
Initially, low = 0 and high = 8. Therefore:
mid = (0 + 8) / 2
mid = 4
The middle element is 50. Since 70 is greater than 50, we eliminate the left half and search the right half.
The new search range contains 60, 70, 80, and 90. We repeat the process until the target is found.
3. How Does Binary Search Work?
Binary Search maintains three important variables:
- low: The starting index of the current search range.
- high: The ending index of the current search range.
- mid: The middle index of the current search range.
Step-by-Step Process
- Initialize low to 0 and high to n - 1.
- Calculate the middle index using low + (high - low) / 2.
- Compare the middle element with the target.
- If both are equal, return the middle index.
- If the target is smaller, update high to mid - 1.
- If the target is greater, update low to mid + 1.
- Repeat while low is less than or equal to high.
- If the search range becomes empty, return -1.
4. Binary Search Algorithm
The basic pseudocode for Binary Search is:
BinarySearch(arr, n, target):
low = 0
high = n - 1
while low <= high:
mid = low + (high - low) / 2
if arr[mid] == target:
return mid
else if target < arr[mid]:
high = mid - 1
else:
low = mid + 1
return -1
5. Iterative Binary Search Implementation in C++
The iterative approach uses a while loop to repeatedly reduce the search range.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int n, int target) {
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
}
else if (target < arr[mid]) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 70;
int result = binarySearch(arr, n, target);
if (result != -1) {
cout << "Element found at index: " << result;
}
else {
cout << "Element not found";
}
return 0;
}
Output
Element found at index: 6
6. Understanding the C++ Code
Step 1: Initialize the Search Range
int low = 0;
int high = n - 1;
The variable low points to the first array element, while high points to the last array element.
Step 2: Continue While the Search Range Exists
while (low <= high)
The loop continues as long as the search range contains at least one element.
Step 3: Calculate the Middle Index
int mid = low + (high - low) / 2;
This calculates the middle position of the current search range. This expression is preferred over (low + high) / 2 because it avoids possible integer overflow when the index values are very large.
Step 4: Check Whether the Target Is Found
if (arr[mid] == target) {
return mid;
}
If the middle element matches the target, the function immediately returns its index.
Step 5: Search the Left Half
else if (target < arr[mid]) {
high = mid - 1;
}
If the target is smaller than the middle element, all elements from mid to high can be eliminated.
Step 6: Search the Right Half
else {
low = mid + 1;
}
If the target is greater than the middle element, all elements from low to mid can be eliminated.
Step 7: Return -1 if Not Found
return -1;
If the loop finishes without finding the target, the function returns -1 to indicate that the element is not present.
7. Dry Run of Binary Search
Let us search for 70 in the following sorted array:
arr = [10, 20, 30, 40, 50, 60, 70, 80, 90]
Target:
target = 70
| Step | Low | High | Mid | arr[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 8 | 4 | 50 | 70 is greater. Search right half. |
| 2 | 5 | 8 | 6 | 70 | Target found. |
Final result:
Element found at index: 6
8. Binary Search When the Element Is Not Found
Consider searching for 35 in the following sorted array:
arr = [10, 20, 30, 40, 50, 60, 70]
target = 35
| Step | Low | High | Mid | arr[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 40 | 35 is smaller. Search left. |
| 2 | 0 | 2 | 1 | 20 | 35 is greater. Search right. |
| 3 | 2 | 2 | 2 | 30 | 35 is greater. Search right. |
| 4 | 3 | 2 | - | - | Search range is empty. |
Element not found
9. Recursive Binary Search
Binary Search can also be implemented using recursion. In this approach, the function calls itself with a smaller search range after every comparison.
How Recursion Works
- Check whether low is greater than high. If so, return -1.
- Calculate the middle index.
- If the middle element matches the target, return mid.
- If the target is smaller, recursively search the left half.
- Otherwise, recursively search the right half.
C++ Code
#include <iostream>
using namespace std;
int binarySearch(int arr[], int low, int high, int target) {
if (low > high) {
return -1;
}
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid;
}
else if (target < arr[mid]) {
return binarySearch(arr, low, mid - 1, target);
}
else {
return binarySearch(arr, mid + 1, high, target);
}
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 60;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1) {
cout << "Element found at index: " << result;
}
else {
cout << "Element not found";
}
return 0;
}
Output
Element found at index: 5
10. Iterative vs Recursive Binary Search
| Feature | Iterative Binary Search | Recursive Binary Search |
|---|---|---|
| Implementation | Uses a loop | Uses recursive function calls |
| Time Complexity | O(log n) | O(log n) |
| Auxiliary Space | O(1) | O(log n) due to recursion stack |
| Function Calls | No recursive calls | Multiple recursive calls |
| Memory Usage | Lower | Higher because of the call stack |
| Practical Use | Often preferred for efficiency | Useful for understanding recursion |
11. Time Complexity of Binary Search
Binary Search reduces the search range by approximately half after every comparison.
If the original array contains n elements, the remaining search range is approximately:
After 1 step: n / 2
After 2 steps: n / 4
After 3 steps: n / 8
After k steps: n / 2^k
The search ends when approximately one element remains:
n / 2^k = 1
n = 2^k
k = log2(n)
Therefore, the time complexity of Binary Search is:
O(log n)
| Case | Condition | Time Complexity |
|---|---|---|
| Best Case | Target is the middle element in the first comparison | O(1) |
| Average Case | Several range reductions are needed | O(log n) |
| Worst Case | Target is absent or found after maximum reductions | O(log n) |
12. Space Complexity of Binary Search
Space complexity depends on the implementation method.
Iterative Approach
The iterative implementation uses only a fixed number of variables such as low, high, and mid.
Auxiliary Space: O(1)
Recursive Approach
The recursive implementation creates function calls that remain on the call stack until the search finishes. In the worst case, the recursion depth is logarithmic.
Auxiliary Space: O(log n)
13. Advantages of Binary Search
- Very efficient for large sorted datasets.
- Has O(log n) average and worst-case time complexity.
- Eliminates half of the remaining search range after each comparison.
- Iterative Binary Search requires only O(1) auxiliary space.
- Can be implemented using both iteration and recursion.
- Useful in many searching and boundary-finding problems.
14. Disadvantages of Binary Search
- Requires sorted data.
- Sorting an unsorted collection may require additional time.
- It is less suitable for data structures without efficient random access, such as ordinary linked lists.
- Incorrect boundary updates can cause infinite loops or missed elements.
- It can be more complicated to implement correctly than Linear Search.
15. Applications of Binary Search
- Searching Sorted Arrays: Quickly locating elements in sorted collections.
- Database Systems: Searching ordered indexes and sorted records.
- Dictionary Lookup: Finding words in alphabetically sorted collections.
- Finding Boundaries: Locating the first or last position satisfying a condition.
- Competitive Programming: Solving efficient searching and optimization problems.
- Large Datasets: Reducing the number of comparisons required to find an element.
16. Common Mistakes to Avoid
- Applying Binary Search directly to unsorted data.
- Using incorrect initial values for low and high.
- Forgetting to update low or high after each comparison.
- Using low < high when the implementation must also examine a single remaining element.
- Updating high to mid instead of mid - 1 in the standard inclusive-range implementation.
- Updating low to mid instead of mid + 1.
- Using an overflow-prone middle-index calculation for very large arrays.
- Confusing array indexes with array values.
17. Practice Questions
Basic Questions
- What is Binary Search?
- Why does Binary Search require sorted data?
- What is the divide and conquer approach?
- What are low, high, and mid in Binary Search?
- What is the best-case time complexity of Binary Search?
Intermediate Questions
- Find 40 in the array [10, 20, 30, 40, 50, 60].
- Find 75 in the array [10, 25, 40, 55, 70, 85, 100].
- Explain the difference between iterative and recursive Binary Search.
- Why is O(log n) more efficient than O(n) for large inputs?
- What happens if the array is not sorted?
Programming Practice
- Write a C++ program to implement iterative Binary Search.
- Write a C++ program to implement recursive Binary Search.
- Search for a target element in a sorted array and return its index.
- Modify Binary Search to find the first occurrence of a target element.
- Modify Binary Search to find the last occurrence of a target element.
- Count the number of comparisons performed by Binary Search.
18. Key Takeaways
- Binary Search is based on the divide and conquer technique.
- It works on sorted collections.
- It compares the target with the middle element.
- It eliminates half of the remaining search range after each comparison.
- Its best-case time complexity is O(1).
- Its average and worst-case time complexity are O(log n).
- Iterative auxiliary space complexity is O(1).
- Recursive auxiliary space complexity is O(log n).