We are going to implement a binary search algorithm in Java.
The binary search algorithm works on a sorted array.
Steps:
- Set low to 0 and high to the length of the array minus one.
- While low <= high:
a. Compute mid = low + (high - low) / 2 (to avoid overflow).
b. If the element at mid is the target, return mid.
c. If the element at mid is less than the target, set low = mid + 1.
d. Otherwise, set high = mid - 1.
- If the target is not found, return -1.
We'll write a method that takes a sorted array of integers and a target integer and returns the index of the target or -1 if not found.
Here's a clean implementation of the binary search algorithm in Java:
public class BinarySearch {
/**
* Performs binary search on a sorted array.
*
* @param arr Sorted array of integers
* @param target Value to search for
* @return Index of target if found, otherwise -1
*/
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
// Use this to prevent integer overflow
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
return -1; // Target not found
}
/**
* Recursive implementation (optional)
*/
public static int binarySearchRecursive(int[] arr, int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right);
} else {
return binarySearchRecursive(arr, target, left, mid - 1);
}
}
// Example usage
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15};
int target = 7;
// Iterative version
int result = binarySearch(sortedArray, target);
if (result != -1) {
System.out.println("Target found at index: " + result);
} else {
System.out.println("Target not found");
}
// Recursive version
int recursiveResult = binarySearchRecursive(sortedArray, target, 0, sortedArray.length - 1);
System.out.println("Recursive search result: " + recursiveResult);
}
}
Key Features:
-
Time Complexity: O(log n) - significantly faster than linear search for large datasets
-
Space Complexity:
- Iterative version: O(1) (constant space)
- Recursive version: O(log n) (stack space for recursion)
-
Important Implementation Details:
mid = left + (right - left) / 2 prevents integer overflow that can occur with (left + right) / 2
- Requires sorted input array (ascending order in this implementation)
- Handles edge cases (empty array, single element, etc.)
- Returns
-1 when target is not found
Usage Notes:
-
Precondition: The input array must be sorted in ascending order
-
Variations: You can modify for:
- Descending order arrays (reverse comparison logic)
- Different data types (use generics or overload methods)
- Custom comparison logic (implement Comparator interface)
-
When to Use:
- Large sorted datasets
- Frequent search operations on static data
- When you need guaranteed O(log n) performance
Common Pitfalls to Avoid:
- ❌ Using
(left + right) / 2 (can overflow with large arrays)
- ❌ Forgetting to update
left/right correctly (mid ± 1, not just mid)
- ❌ Not handling base case in recursive version
- ❌ Using on unsorted arrays (will give incorrect results)
The iterative version is generally preferred in production code due to:
- No recursion overhead
- No risk of stack overflow for large arrays
- Better memory efficiency
Would you like me to add:
- Generic version (for any comparable type)?
- Version that returns insertion point when not found?
- Performance benchmarks/comparisons?
- Explanation of why overflow can happen with
(left + right) / 2?