In computer science, binary search, also known as half-interval search,logarithmic search,or binary chop,is a search algorithm that finds the position of a target value within a sorted array.
The Binary Search Algorithm is a way to find a specific item in a sorted list
quickly. Instead of checking each item one by one, it works by repeatedly cutting the list in half. If the item youβre looking for is in the first half, it ignores
the second half, and vice versa. This process keeps narrowing down the search until the item is found. Because it halves the list each time, itβs very efficient and works in O(logn) time, which is much faster than checking every item.
Binary Search Explained with a Book Example (Searching for a Page) Imagine you have a large book and you want to find a particular page (say page 450) quickly. Instead of flipping through one page at a time (linear search), you can use binary search to find it much faster
Steps to Find Page 450 Using Binary Search:
Step 1: Open the Middle Page
Step 2: Compare the Page Number
Step 3: Repeat in the Correct Half
Step 4: Keep Narrowing Down
Binary search is an efficient method for finding a specific value in a sorted list. Instead of scanning each element one by one, it speeds up the process by repeatedly cutting the search space in half. The search begins by identifying the middle element of the list. If this middle element matches the target value, the search is complete. However, if the target is smaller than the middle element, the search continues in the left half of the list. Conversely, if the target is larger, the search shifts to the right half. This process repeats until the target is found or the search space becomes empty. By reducing the number of elements to check at each step, binary search is significantly faster than a linear search, making it ideal for large datasets
The Binary Search Algorithm is a quick way to find a number in a sorted list by repeatedly cutting the search space in half.
low
to the first index (0) and high
to the last index (length-1).mid = Math.floor((low + high) / 2)
.low = mid + 1
).high = mid - 1
).low > high
(element not in array).public class BinarySearch {
public static int binarySearch(int[] array, int target) {
int start = 0;
int end = array.length - 1;
// Repeat until the search space is exhausted
while (start <= end) {
int middle = start + (end - start) / 2;
// If middle element is the target, return its index
if (array[middle] == target) {
return middle;
}
// If target is smaller, search in the left half
else if (array[middle] > target) {
end = middle - 1;
}
// If target is larger, search in the right half
else {
start = middle + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50}; // <--- this is our search space
int target = 30; // <--- this is our target element
System.out.println("Index of " + target + ": " + binarySearch(arr, target));
}
}
Given a sorted array A
of n
elements and a target value T
, we find the index of T
using recursion.
Define the recursive function
A
, T
, start
, and end
as inputs.start > end
, that means the element is not present, so return -1
.Find the middle element
mid = start + (end - start) / 2
to avoid integer overflow.Compare the middle element with the target
A[mid] == T
, return mid
because we found the element.A[mid] > T
, that means the element is in the left half, so call the function again with end = mid - 1
:return binarySearch(A, T, start, mid - 1);
A[mid] < T
, the element must be in the right half, so call the function with start = mid + 1
:return binarySearch(A, T, mid + 1, end);
Recursion continues
start > end
), which means the element is not in the array.Final answer
mid
.-1
to indicate that the target is missing.public class BinarySearchRecursive {
public static int binarySearch(int[] array, int target, int start, int end) {
if (start > end) return -1; // Base case: not found
int middle = start + (end - start) / 2; // Prevent overflow
if (array[middle] == target) return middle; // Found
else if (array[middle] > target) return binarySearch(array, target, start, middle - 1); // Left half
else return binarySearch(array, target, middle + 1, end); // Right half
}
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;
int index = binarySearch(arr, target, 0, arr.length - 1);
System.out.println("Index of " + target + ": " + index);
}
}
Approach | Implementation | Space Complexity | Time Complexity |
---|---|---|---|
Iterative | Uses a while loop to narrow the search range | O(1) (constant extra space) | O(log n) |
Recursive | Calls itself with updated S and E | O(log n) (due to recursive stack) | O(log n) |
mid = s + (e - s) / 2
in C++?mid = s + (e - s) // 2
to prevent overflow.int
is -2^31
to 2^31 - 1
.mid = (s + e) / 2
, it may cause integer overflow for large values of s
and e
.Execute The code below to see the difference between the two methods
# [ (x-1) x ]
# 2^31 - 2 2^31 - 1
s = 2**31 - 2
e = 2**31 - 1
print("int max: ", 2**31 - 1) # -> 2147483647
print("normal way: ", s + e / 2) # -> 3221225469.5
print("modified way: ", s + (e - s) / 2) # -> 2147483646.5