01 / 21

Binary Search
in Java

Master the divide-and-conquer strategy that finds elements in a sorted array with \( O(\log n) \) efficiency: conceptually and with Arrays.binarySearch.

Java Algorithms

What Is Binary Search?

Binary search is an algorithm that finds a target value inside a sorted array by repeatedly cutting the search space in half. Instead of checking every element, it asks: "Is the target in the left half or the right half?"

Why Speed Matters

Linear Search
Checks every element one by one. On 1,000,000 items, up to 1,000,000 comparisons.
Binary Search
Halves the search space each step. On 1,000,000 items, at most 20 comparisons.

The Key Prerequisite

Binary search only works on sorted data. If the array is not sorted, the algorithm cannot reliably decide which half to discard, and it may return incorrect results.

Sorted (valid) 2 5 8 12 19 ✓ Unsorted (invalid) 12 5 19 ✕

The Algorithm Step by Step

1
Set pointers: \(\texttt{low} = 0\), \(\texttt{high} = n - 1\).
2
Compute midpoint: \(\texttt{mid} = \texttt{low} + \lfloor(\texttt{high} - \texttt{low}) / 2\rfloor\).
3
Compare: If \(\texttt{arr[mid]} = \texttt{target}\), found it. If \(\texttt{arr[mid]} < \texttt{target}\), set \(\texttt{low} = \texttt{mid} + 1\). Otherwise, set \(\texttt{high} = \texttt{mid} - 1\).
4
Repeat until \(\texttt{low} > \texttt{high}\) (not found) or you find the target.

Visual Walkthrough

Searching for target = 23 in the sorted array below:

Index: 0 1 2 3 4 5 6 7 Step 1 3 7 11 15 19 23 30 42 mid=3 (15<23, go right) Step 2 3 7 11 15 19 23 30 42 mid=5: 23 = 23 ✓ Found at index 5! Only 2 comparisons instead of 6 (linear) Search space: 8 → 4 → Found

Time Complexity Analysis

Best Case
\( O(1) \): the target is at the very first midpoint.
Average Case
\( O(\log n) \): each step halves the remaining elements.
Worst Case
\( O(\log n) \): target is at the very end, or not present at all.

Linear vs Binary Search

Linear Search Binary Search
Requires Sorting? No Yes
Time Complexity \( O(n) \) \( O(\log n) \)
\( n = 1{,}024 \) (max steps) 1,024 11
\( n = 1{,}000{,}000 \) (max steps) 1,000,000 20
Best For Small or unsorted data Large sorted datasets

How to Apply Binary Search

1
Confirm sorted order: is the array already sorted? If not, call Arrays.sort(arr).
2
Choose your tool: use Arrays.binarySearch(arr, target) for the built-in method, or write the loop yourself for practice.
3
Interpret the result: a non-negative return value is the index of the target. A negative value means not found.
4
Handle not-found: Arrays.binarySearch returns \( -(insertion\text{ }point) - 1 \) when the target is absent.

Writing It Yourself

public static int binarySearch(int[] arr, int target) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (arr[mid] == target) { return mid; // found } else if (arr[mid] < target) { low = mid + 1; // search right half } else { high = mid - 1; // search left half } } return -1; // not found }

Using Arrays.binarySearch

import java.util.Arrays; int[] arr = {2, 5, 8, 12, 19, 23, 30, 42}; int idx = Arrays.binarySearch(arr, 23); // idx = 5 (found at index 5) int missing = Arrays.binarySearch(arr, 10); // missing = -4 (not found; insertion point would be index 3)

Example 1: Finding a Score

A teacher stores sorted test scores: {55, 62, 74, 81, 88, 93, 97}. Does a student with score 88 exist?

int[] scores = {55, 62, 74, 81, 88, 93, 97}; int result = Arrays.binarySearch(scores, 88); if (result >= 0) { System.out.println("Found at index " + result); } else { System.out.println("Not found"); } // Output: Found at index 4

Example 2: Target Not Found

Search for 70 in the same scores array: {55, 62, 74, 81, 88, 93, 97}.

int result = Arrays.binarySearch(scores, 70); // result = -3 // Insertion point = -(-3) - 1 = 2 // 70 would go at index 2 (between 62 and 74)
55 62 70 goes here 74 81 88 93 97 index 2

Example 3: String Arrays

Arrays.binarySearch also works on String arrays (sorted lexicographically).

String[] names = {"Alice", "Bob", "Eve", "Mallory", "Trent"}; int idx = Arrays.binarySearch(names, "Eve"); // idx = 2 int idx2 = Arrays.binarySearch(names, "Charlie"); // idx2 = -3 (would insert at index 2)

Common Mistakes

✕ Unsorted Array
Calling binarySearch on an unsorted array gives undefined behavior: the result is unpredictable.
✕ Wrong Midpoint Formula
Using \((\texttt{low} + \texttt{high}) / 2\) can overflow for large arrays. Always use \(\texttt{low} + (\texttt{high} - \texttt{low}) / 2\).
✕ Off-by-One Errors
Forgetting to use \(\texttt{<=}\) in the while condition, or not updating \(\texttt{low/high}\) past mid, causes infinite loops.
✕ Ignoring Negative Returns
Treating the return value of Arrays.binarySearch as an index when it is negative causes ArrayIndexOutOfBoundsException.

Summary at a Glance

Concept Detail
Prerequisite Array must be sorted
Time Complexity \( O(\log n) \)
Space Complexity \( O(1) \) iterative, \( O(\log n) \) recursive
Java Built-in Arrays.binarySearch(arr, key)
If Found Returns the index (non-negative)
If Not Found Returns \( -(insertion\text{ }point) - 1 \)
Safe Midpoint \(\texttt{low} + (\texttt{high} - \texttt{low}) / 2\)

Question 1 of 5

What is the most important prerequisite for binary search to work correctly?

Question 2 of 5

What is the worst-case time complexity of binary search on an array of \( n \) elements?

Question 3 of 5

Given int[] arr = {10, 20, 30, 40, 50}, what does Arrays.binarySearch(arr, 35) return?

Question 4 of 5

Why is low + (high - low) / 2 preferred over (low + high) / 2 when computing the midpoint?

Question 5 of 5

In a hand-written binary search, what happens if you use \(\texttt{while (low < high)}\) instead of \(\texttt{while (low <= high)}\)?