Binary Search in Java: Iterative, Recursive and Built-in

admin5 min read
In this tutorial
  1. The idea
  2. Iterative implementation
  3. The overflow bug
  4. Recursive implementation
  5. Finding the first or last occurrence
  6. Using the built-in methods
  7. Binary search beyond arrays
  8. Common mistakes
  9. Summary

Imagine looking for a name in a printed phone book. You would not start at page one and read every entry. You would open somewhere in the middle, see whether the name comes before or after, and throw away half the book. Repeat a few times and you have found it. That is binary search, and it is one of the most important algorithms you will learn.

The idea

Binary search works on a sorted array:

  1. Look at the middle element.
  2. If it is the target, you are done.
  3. If the target is smaller, search the left half; if bigger, search the right half.
  4. Repeat until you find it or the range is empty.

Each step halves the search space. For a million elements, linear search may take a million comparisons; binary search takes at most 20, because 2²⁰ is just over a million. That makes its time complexity O(log n).

Iterative implementation

public class BinarySearch {

    /** Returns the index of target in sorted array a, or -1 if absent. */
    static int search(int[] a, int target) {
        int low = 0;
        int high = a.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;   // avoids integer overflow
            if (a[mid] == target) {
                return mid;
            } else if (a[mid] < target) {
                low = mid + 1;                  // target is in the right half
            } else {
                high = mid - 1;                 // target is in the left half
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] prices = {120, 340, 560, 780, 910, 1500, 2200, 3100};
        System.out.println(search(prices, 910));  // 4
        System.out.println(search(prices, 120));  // 0
        System.out.println(search(prices, 3100)); // 7
        System.out.println(search(prices, 999));  // -1
    }
}

Tracing an example

Searching for 910 in [120, 340, 560, 780, 910, 1500, 2200, 3100]:

  • low=0, high=7, mid=3: a[3]=780 is less than 910, so low=4.
  • low=4, high=7, mid=5: a[5]=1500 is greater than 910, so high=4.
  • low=4, high=4, mid=4: a[4]=910. Found at index 4.

Three comparisons instead of five.

The overflow bug

Many textbooks used to write int mid = (low + high) / 2;. If low and high are both large (over about a billion), low + high overflows int and becomes negative, causing an ArrayIndexOutOfBoundsException. This bug sat in the JDK’s own Arrays.binarySearch for years before it was fixed in 2006.

low + (high - low) / 2 gives the same result without overflow. (low + high) >>> 1 also works, because the unsigned shift treats the overflowed sum correctly.

Recursive implementation

static int searchRecursive(int[] a, int target, int low, int high) {
    if (low > high) {
        return -1;                       // base case: empty range
    }
    int mid = low + (high - low) / 2;
    if (a[mid] == target) {
        return mid;
    }
    return a[mid] < target
            ? searchRecursive(a, target, mid + 1, high)
            : searchRecursive(a, target, low, mid - 1);
}

// call it with: searchRecursive(prices, 910, 0, prices.length - 1)

The recursive version mirrors the idea neatly, but the iterative version uses constant memory, so it is usually preferred in production code.

Finding the first or last occurrence

With duplicates, plain binary search returns some matching index, not necessarily the first. A small change finds the first occurrence: when you find a match, record it and keep searching to the left.

static int firstOccurrence(int[] a, int target) {
    int low = 0, high = a.length - 1, result = -1;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (a[mid] == target) {
            result = mid;
            high = mid - 1;        // keep looking left
        } else if (a[mid] < target) {
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return result;
}

For the last occurrence, set low = mid + 1 on a match instead. With both, you can count occurrences of a value in O(log n): last - first + 1.

Using the built-in methods

You rarely need to write binary search yourself in application code. Java provides it:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

int[] nums = {3, 8, 15, 23, 42};
int i = Arrays.binarySearch(nums, 23);        // 3
int j = Arrays.binarySearch(nums, 10);        // -3

List<String> names = List.of("Ada", "Bola", "Chidi", "Tunde"); // must be sorted
int k = Collections.binarySearch(names, "Chidi"); // 2

When the element is missing, the built-in methods return -(insertionPoint) - 1. For 10, the insertion point is 2 (between 8 and 15), so the result is -3. You can recover the insertion point with -(result) - 1, which is useful for keeping a list sorted as you insert into it.

Binary search beyond arrays

The real power of binary search is the pattern: whenever an answer space is sorted, or a condition switches from false to true exactly once, you can binary search it. Examples:

  • Finding the square root of a number to a given precision.
  • Finding the first bad version in a series of releases.
  • Finding the minimum capacity that lets you ship packages within D days (a popular LeetCode problem).
/** Integer square root: the largest r with r*r <= n. */
static int sqrt(int n) {
    int low = 0, high = n, ans = 0;
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if ((long) mid * mid <= n) {
            ans = mid;
            low = mid + 1;
        } else {
            high = mid - 1;
        }
    }
    return ans;
}
// sqrt(50) == 7

Common mistakes

  • Searching an unsorted array. The result is meaningless. Sort first, or use a HashSet for lookups.
  • Using low < high instead of low <= high in the classic version, which skips the last candidate.
  • Forgetting + 1 / - 1 when moving the bounds, which can loop forever.
  • Overflow in (low + high) / 2, and in mid * mid (cast to long).

Summary

  • Binary search halves a sorted search space each step: O(log n) time.
  • Use mid = low + (high - low) / 2 to avoid overflow.
  • The iterative version uses O(1) memory; the recursive version uses O(log n) stack.
  • Variations find first and last occurrences and solve “search the answer” problems.
  • In everyday code, use Arrays.binarySearch and Collections.binarySearch.

Ask a question or leave a comment

Your email address will not be published. Required fields are marked *