Binary Search is one of the most efficient searching algorithms used on sorted arrays. It works by repeatedly dividing the search interval in half, reducing the time complexity to O(log n). In this article, weβll walk through a clean implementation of binary search in Java with a practical example.
π§ How Binary Search Works
The algorithm compares the target value to the middle element of the array:
- If they match, it returns the index.
- If the target is smaller, search the left half.
- If the target is larger, search the right half.
- Repeat until the value is found or the range becomes invalid.
π§Ύ Java Code Example
java
public class BinarySearch {
// Binary search function
public static int binarySearch(int[] array, int key) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Safe midpoint to avoid overflow
if (array[mid] == key) {
return mid; // Key found
} else if (array[mid] < key) {
low = mid + 1; // Search in right half
} else {
high = mid - 1; // Search in left half
}
}
return -1; // Key not found
}
public static void main(String[] args) {
int[] sortedArray = {2, 3, 4, 10, 40};
int key = 10;
int result = binarySearch(sortedArray, key);
if (result == -1) {
System.out.println("Element not present in array");
} else {
System.out.println("Element found at index " + result);
}
}
}
π Explanation
- Function:
binarySearch(int[] array, int key)
- Input: Sorted integer array and the value to search.
- Output: Index of the value in the array, or
-1
if not found.
π Key Variables:
VariableMeaninglow
Start of search rangehigh
End of search rangemid
Middle of the current range
β
Example Output
pgsql
Element found at index 3
The key 10
is found at index 3
in the array {2, 3, 4, 10, 40}
.
π Summary
- π§ Binary Search is optimal for sorted arrays.
- β‘ Time Complexity:
O(log n)
- π Works by halving the search range until the target is found or not present.
This is a core concept in many coding interviews, especially for roles that focus on problem-solving and algorithmic thinking. If youβre preparing for interviews, make sure youβre also familiar with recursive implementations and how binary search applies to real-world problems like finding boundaries, ranges, and more.