Java Array Program · A22
Binary Search in a Sorted Array in Java
Look at the middle element. If it is too small, the key can only be in the right half; if it is too large, only in the left half. Each step halves the range.
Problem Statement
Given an array sorted in ascending order and a key, return the index of the key, or -1 if it is not present.
The method must run in O(log n) time.
Input/Output Examples
[2, 5, 8, 12, 16, 23, 38], key = 23Output5Explanation: 23 is at index 5.[2, 5, 8, 12, 16, 23, 38], key = 7Output-1Explanation: 7 would sit between 5 and 8, but it is not there.[], key = 4Output-1Explanation: nothing to search.Visual Explanation
- lo=0, hi=6mid 31212 < 23 search right
- lo=4, hi=6mid 52323 = 23 found
- Done2 comparisons for 7 elementsindex 5
[2, 5, 8, 12, 16, 23, 38]: the middle value 12 is too small, so the left half is discarded; the next middle value is the key.Each comparison throws away half of the remaining range, so at most about log2 n + 1 comparisons are needed: 20 comparisons are enough for a million elements.
Approaches
Both approaches halve the range in the same way. One uses a loop; the other recurses.
Approach 1: Iterative (Recommended)
Idea: maintain lo and hi and move one of them past the middle after each comparison.
- Set
lo = 0andhi = n - 1. - While
lo ≤ hi, computemid = lo + (hi - lo) / 2. - Return
midon a match; otherwise moveloorhi. - Return
-1when the range is empty.
Time: O(log n) · Space: O(1).
Approach 2: Recursive
Idea: check the middle, then recurse into the half that can still contain the key.
- Return
-1iflo > hi. - Return
midon a match. - Recurse into the right or left half.
Time: O(log n) · Space: O(log n). One stack frame per halving.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Iterative (Recommended)
lo + (hi - lo) / 2 avoids the overflow that (lo + hi) / 2 can cause for very large arrays.
import java.util.Arrays;
public class BinarySearchIterative {
// Halve the search range [lo, hi] until the key is found or the range is empty
static int binarySearch(int[] arr, int key) {
int lo = 0;
int hi = arr.length - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; // avoids overflow of (lo + hi)
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
lo = mid + 1;
} else {
hi = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38};
System.out.println(Arrays.toString(arr) + ", key=23 -> " + binarySearch(arr, 23));
System.out.println(Arrays.toString(arr) + ", key=7 -> " + binarySearch(arr, 7));
System.out.println("[], key=4 -> " + binarySearch(new int[0], 4));
}
}
[2, 5, 8, 12, 16, 23, 38], key=23 -> 5 [2, 5, 8, 12, 16, 23, 38], key=7 -> -1 [], key=4 -> -1
Time complexity: O(log n) · Space complexity: O(1).
Approach 2: Recursive
Mirrors the definition, but the loop version uses no stack space.
import java.util.Arrays;
public class BinarySearchRecursive {
static int binarySearch(int[] arr, int key) {
return search(arr, key, 0, arr.length - 1);
}
// Each call looks at the middle and recurses into the half that can contain the key
private static int search(int[] arr, int key, int lo, int hi) {
if (lo > hi) {
return -1;
}
int mid = lo + (hi - lo) / 2;
if (arr[mid] == key) {
return mid;
}
return arr[mid] < key ? search(arr, key, mid + 1, hi) : search(arr, key, lo, mid - 1);
}
public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38};
System.out.println(Arrays.toString(arr) + ", key=23 -> " + binarySearch(arr, 23));
System.out.println(Arrays.toString(arr) + ", key=7 -> " + binarySearch(arr, 7));
System.out.println("[], key=4 -> " + binarySearch(new int[0], 4));
}
}
[2, 5, 8, 12, 16, 23, 38], key=23 -> 5 [2, 5, 8, 12, 16, 23, 38], key=7 -> -1 [], key=4 -> -1
Time complexity: O(log n) · Space complexity: O(log n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative | O(log n) | O(1) |
| Recursive | O(log n) | O(log n) |
Here n is the length of the array. The range halves at every step, so both versions make O(log n) comparisons.
Interview Tips and Recommended Approach
- The array must be sorted. Binary search on unsorted data gives wrong answers silently.
- Use the overflow-safe midpoint.
(lo + hi) / 2overflowed in the JDK itself for years. - Get the loop condition right.
lo ≤ hiwithmid ± 1avoids infinite loops. - Know
Arrays.binarySearch(). It returns-(insertion point) - 1for a missing key, not just-1.
Recommended Approach: Iterative
Why: it runs in logarithmic time with constant memory and is the template for many variants, such as first or last occurrence and search in rotated arrays.