Binary Search
Binary Search is one of the most efficient search algorithms used to find an element in a sorted array or list. Unlike linear search, which checks each element sequentially, binary search divides the search space in half with each comparison, making it significantly faster for large datasets.
Binary search operates on the principle of divide and conquer. It repeatedly divides the search interval in half, checking whether the target value is present in the left or right half of the array. This drastically reduces the number of comparisons needed, especially when compared to linear search, which can have time complexities of O(n).
Binary search follows a simple set of steps to find an element in a sorted array:
low
as the starting index (0) and high
as the last index of the array.low
is less than or equal to high
:
mid = (low + high) // 2
.mid
.high
pointer to mid - 1
.low
pointer to mid + 1
.-1
, indicating that the target is not in the array.Let's look at how to implement binary search in different programming languages:
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid # Return the index where the target is found
elif arr[mid] < target:
low = mid + 1 # Narrow the search to the right half
else:
high = mid - 1 # Narrow the search to the left half
return -1 # Return -1 if the element is not found
# Sample usage
arr = [1, 3, 5, 7, 9, 11, 13]
target = 7
result = binary_search(arr, target)
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
In Python, binary search is implemented using two pointers, low
and high
, which are updated during each iteration to search the relevant half of the array.
function binarySearch(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === target) {
return mid; // Return index if target is found
}
else if (arr[mid] < target) {
low = mid + 1; // Narrow the search to the right half
} else {
high = mid - 1; // Narrow the search to the left half
}
}
return -1; // Return -1 if the element is not found
}
// Sample usage
const arr = [1, 3, 5, 7, 9, 11, 13];
const target = 7;
const result = binarySearch(arr, target);
if (result !== -1) {
console.log(`Element found at index ${result}`);
} else {
console.log("Element not found");
}
In JavaScript, binary search is also implemented with two pointers (low
and high
) that move based on whether the target is smaller or larger than the middle element.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int size, int target) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // Return the index where the target is found
} else if (arr[mid] < target) {
low = mid + 1; // Narrow the search to the right half
} else {
high = mid - 1; // Narrow the search to the left half
}
}
return -1; // Return -1 if the element is not found
}
int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13};
int target = 7;
int size = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, size, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found" << endl;
}
return 0;
}
In C++, binary search follows the same logic as in Python and JavaScript, using a while
loop to adjust the search range.
Binary search has a time complexity of O(log n), which is significantly better than linear search’s O(n). This logarithmic complexity arises because the search space is halved with each iteration.
Binary search is highly efficient, especially when working with large datasets, as it dramatically reduces the number of comparisons required compared to linear search.
Binary search is widely used in many areas of computer science and practical applications, including:
std::binary_search
in C++ or bisect
module in Python, which developers use for efficient searching.