Binary Search and Its Powerful Applications

Anshu
5 min readJun 16, 2023

--

Introduction

In the realm of computer science, the ability to efficiently search through vast amounts of data is of paramount importance. Binary search, a fundamental algorithmic technique, stands as a shining example of how a simple concept can yield powerful results. In this post, we will delve into the workings of binary search and explore its wide-ranging applications across various domains.

Understanding Binary Search

Binary search is an algorithmic approach used to locate a specific element within a sorted array or list. It follows a divide-and-conquer strategy, repeatedly dividing the search space in half until the desired element is found or determined to be absent. Its key advantage lies in its time complexity, which is logarithmic — O(log n) — whereas a simple linear search would have a time complexity of O(n) in the worst case.

Algorithmic Steps:

1. Begin with a sorted array or list: Binary search requires the input data to be sorted in ascending or descending order. This sorted property allows the algorithm to make informed decisions during the search process.

2. Set the lower and upper boundaries: Initially, the lower boundary is set to the first index of the array, and the upper boundary is set to the last index.

3. Compute the middle index: Calculate the middle index of the search space by taking the average of the lower and upper boundaries. This is done by using the formula: `middle = (lower + upper) / 2`.

4. Compare the middle element: Compare the element at the middle index with the desired value. If they are equal, the element is found, and its index is returned.

5. Adjust the boundaries: If the middle element is greater than the desired value, it means the desired element, if present, must be in the left half of the array. In this case, set the new upper boundary to `middle — 1`. If the middle element is less than the desired value, it means the desired element, if present, must be in the right half of the array. In this case, set the new lower boundary to `middle + 1`.

6. Repeat steps 3–5: Repeat the above steps, recalculating the middle index based on the updated boundaries, until the desired element is found or the boundaries overlap, indicating that the element is not present in the array.

Binary Search - Recursion Tree

Code

#include <iostream>
#include <vector>

using namespace std;

int binarySearch(const vector<int>& arr, int target) {
int low = 0;
int high = arr.size() - 1;

while (low <= high) {
int mid = low + (high - low) / 2;

if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}

return -1; // Element not found
}

int main() {
vector<int> arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int target = 10;

int result = binarySearch(arr, target);

if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found" << endl;
}

return 0;
}

Code Explanation

In this C++ code, the binarySearch function takes in a sorted vector arr and a target value target to search for. It initializes the lower boundary low to 0 and the higher boundary high to the last index of the array. The while loop continues until the lower boundary exceeds the higher boundary.

Inside the loop, the middle index mid is calculated using (low + (high - low) / 2), which avoids potential overflow. The middle element is then compared with the target value. If they are equal, the function returns the index of the element.

If the middle element is less than the target value, the lower boundary low is updated to mid + 1, as the desired element, if present, must be in the right half of the array. If the middle element is greater than the target value, the higher boundary high is updated to mid - 1, as the desired element, if present, must be in the left half of the array.

If the element is not found after the while loop terminates, the function returns -1 to indicate that the element is not present in the array.

The code also includes a main function where the binarySearch function is called with a sample vector and target value. The result is then checked, and an appropriate message is printed based on whether the element was found or not.

Feel free to modify the vector and target value to test the binary search algorithm with different inputs.

Applications of Binary Search

1. Searching in Sorted Arrays: Binary search’s most common application is searching for a particular element in a sorted array. Its efficiency makes it ideal for tasks like finding an item in a dictionary or searching for a specific value in large datasets. For example, a phone book can be implemented as a sorted array, and binary search allows quick lookups of phone numbers based on names.

2. Finding Closest Values: Binary search can be employed to find the nearest value to a given target value. This is particularly useful when dealing with numerical datasets or when designing algorithms that require matching or approximation. For instance, in financial applications, binary search can be used to determine the best match for a specific stock price in a sorted list of stock prices.

3. Spell Checkers and Autocorrect: In natural language processing, binary search plays a crucial role in spell checkers and autocorrect systems. By implementing a dictionary with sorted words, binary search enables quick suggestions for misspelled words or efficient dictionary lookups. It allows for faster identification of potential correct words or detecting and offering corrections for mistyped words.

4. Game Development: Binary search finds application in game development for tasks such as collision detection and pathfinding. It allows for efficient identification of objects that intersect or come into proximity with each other, improving performance and gameplay experience. For example, in a game that involves shooting projectiles at moving targets, binary search

Conclusion

Binary search, with its elegant simplicity and remarkable efficiency, remains a staple algorithm in computer science. By leveraging its divide-and-conquer approach, we unlock the ability to search through sorted arrays with optimal time complexity. As we have seen, its applications span a multitude of domains, from traditional software development to artificial intelligence and beyond. Understanding and harnessing the power of binary search equips us with a valuable tool to tackle complex problems efficiently, propelling us forward in the ever-evolving world of technology.

--

--

Anshu

3nd-year CSE undergraduate student at Chandigarh University with an interest in solving and developing technical solutions.