AP Computer Science A · Study guide

Binary Search

AP® Computer Science A · Data Collections

Binary Search

Searching sorted data by starting in the middle and eliminating half of the remaining elements at every step: tracing low, high, and mid, iterative and recursive versions, why sorted order is required, and why binary search is usually faster than linear search.

Big Picture

Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the remaining elements in each step until the desired value is found or all elements have been eliminated. It is typically more efficient than linear search, and it can be written either iteratively or recursively. Tracing it means tracking the range that remains, usually with variables named low and high, and the middle index checked at each step.

1Sorted Data First

Binary search is built on one fact about sorted data: if the middle element is smaller than the value being sought, then every element before it is smaller too, so none of them can be the target. One comparison therefore rules out a whole half of the data. Data must be in sorted order to use the binary search algorithm; on unsorted data that reasoning is false, and the search can discard the half that contains the target.

The order can be ascending numbers, alphabetical strings, or any order that the comparisons in the code agree with. If the data is not sorted, a linear search, which assumes nothing about order, is the correct choice, or the data must be sorted first.

Figure 1. Data must be in sorted order to use binary search; on unsorted data it can discard the half that holds the target.
Worked Example 1 Sorted data required

Binary Search on Unsorted Data

42 is in the array below. What does each search return?

Code
public static int binaryFind(int[] a, int target)
{
    int low = 0;
    int high = a.length - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (a[mid] == target)
        {
            return mid;
        }
        else if (a[mid] < target)
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return -1;
}

public static int linearFind(int[] a, int target)
{
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == target)
        {
            return i;
        }
    }
    return -1;
}
Output
-1 2
  1. 1Binary search assumes order. a[3] is 8, less than 42, so it discards indices 0 to 3, including the 42 at index 2 (Figure 1).
  2. 2Linear search assumes nothing and finds 42 at index 2.
Result: The output is -1 2. Data must be in sorted order to use the binary search algorithm.
Common Mistake 1 · Running Binary Search on Unsorted Data

Binary search on unsorted data compiles and runs, but it can return −1 for a value that is present, or find a different occurrence than expected. Check that the data is sorted before choosing binary search.

2Start in the Middle, Eliminate Half

Binary search keeps track of the part of the data that might still hold the target, from index low to index high. At first that is everything: low is 0 and high is the last index. Each step checks the middle index, mid = (low + high) / 2, using integer division, so the middle rounds down when the range has an even number of elements.

If the middle element equals the target, the search is over. If it is smaller than the target, the target can only be to its right, so low becomes mid + 1. If it is larger, the target can only be to its left, so high becomes mid - 1. Either way, the middle element and one half of the range are eliminated.

Figure 2. Binary search starts at the middle of the sorted data and eliminates half of the remaining elements at each step until the value is found.
Steplowhighmida[mid]Compared with 30Next
10632121 < 30low = 4
24654242 > 30high = 4
344430equalreturn 4
Worked Example 2 Iterative

Tracing low, high, and mid

The search prints its range before each check. Predict the output.

Code
public static int binarySearch(int[] a, int target)
{
    int low = 0;
    int high = a.length - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        System.out.println("low " + low + ", high " + high + ", mid " + mid);
        if (a[mid] == target)
        {
            return mid;
        }
        else if (a[mid] < target)
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return -1;
}
Output
low 0, high 6, mid 3
low 4, high 6, mid 5
low 4, high 4, mid 4
4
  1. 1Step 1. mid = (0 + 6) / 2 = 3; a[3] is 21, less than 30, so low becomes 4.
  2. 2Step 2. mid = (4 + 6) / 2 = 5; a[5] is 42, greater than 30, so high becomes 4.
  3. 3Step 3. mid = (4 + 4) / 2 = 4; a[4] is 30: return 4.
Result: The output shows three ranges and then 4. Each step compares the middle element with the target and keeps only the half that can still contain it (Figure 2).
Common Mistake 2 · Setting low = mid Instead of mid + 1

The middle element has already been checked, so the new range must exclude it. With low = mid, a range of two elements can produce the same mid forever, and the loop never ends. Use mid + 1 and mid - 1.

3Tracing Each Step

To determine the result of each iteration, keep a table with one row per step: low, high, mid, the element at mid, the comparison, and the change to the range. Compute mid with integer division every time; most tracing mistakes come from rounding mid up or reusing an old value.

The same steps apply to an ArrayList, using get(mid) and size(), and to strings, using compareTo: a result of 0 means a match, a negative result means the middle word comes earlier than the target, and a positive result means it comes later.

Worked Example 3 ArrayList of strings

Comparing With compareTo

Search a sorted list of words. Predict the output.

Code
public static int findWord(ArrayList<String> list, String target)
{
    int low = 0;
    int high = list.size() - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        int cmp = list.get(mid).compareTo(target);
        if (cmp == 0)
        {
            return mid;
        }
        else if (cmp < 0)
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return -1;
}
Output
4
-1
  1. 1compareTo returns 0 for equal strings, a negative number when the middle word comes earlier, and a positive number when it comes later.
  2. 2"maple": mid 3 is "elm", earlier, so search right; mid 5 is "oak", later, so search left; mid 4 is "maple".
  3. 3"fir" would sit between "elm" and "maple"; the range empties and the result is −1.
Result: The output is 4 and -1. Binary search works on a sorted ArrayList of strings, using compareTo to decide which half to keep.
Common Mistake 3 · Comparing Strings With < or ==

Relational operators do not work on String objects, and == compares references. A binary search of strings decides its direction with compareTo and detects a match with a result of 0.

4The Recursive Version

The binary search algorithm can be written either iteratively or recursively. In the recursive version, the range is passed as parameters: each call checks the middle of its range and, unless it finds the target, returns the result of a call on the half that remains. The parameters low and high capture the progress of the search, just as the loop variables do in the iterative version.

The recursive version has two base cases: a match, which returns mid, and an empty range, low > high, which returns −1. Tracing it is the same as tracing the loop, one call per step; the value found by the last call is returned unchanged through all the earlier calls.

Figure 3. In a recursive binary search, each call receives the half that remains, through its low and high parameters.
IterativeRecursive
Range stored inLocal variables low, highParameters low, high
Stops searching whenlow > high ends the loopBase case low > high returns −1
Keeps the right half bylow = mid + 1;Calling with mid + 1, high
Keeps the left half byhigh = mid - 1;Calling with low, mid - 1
Worked Example 4 Recursive

The Same Search With Recursive Calls

Predict the output (Figure 3).

Code
public static int binSearch(int[] a, int target, int low, int high)
{
    if (low > high)
    {
        return -1;
    }
    int mid = (low + high) / 2;
    System.out.println("search " + low + " to " + high);
    if (a[mid] == target)
    {
        return mid;
    }
    if (a[mid] < target)
    {
        return binSearch(a, target, mid + 1, high);
    }
    return binSearch(a, target, low, mid - 1);
}
Output
search 0 to 6
search 4 to 6
search 6 to 6
6
  1. 1Base cases. low > high means nothing is left: −1. A match returns mid.
  2. 2Recursive calls pass the remaining half: 21 < 57 gives 4 to 6; 42 < 57 gives 6 to 6.
  3. 3The parameters low and high play the role of the loop variables in the iterative version.
Result: The output shows three ranges and then 6. Binary search can be written either iteratively or recursively; both eliminate half of the range at each step.

5When the Value Is Not There

Binary search eliminates half of the remaining elements in each step until the desired value is found or all elements have been eliminated. When every element has been ruled out, low has moved past high: the loop condition low <= high fails, or the recursive base case is reached, and the search returns −1.

At that moment, low is the index where the missing value would belong if it were inserted to keep the data sorted. That observation is not needed to trace a search, but it explains why the range closes exactly between the two neighbors of the missing value.

Worked Example 5 Not found

Eliminating Everything

Search the same array for 20, which is not there.

Code
public static int binarySearch(int[] a, int target)
{
    int low = 0;
    int high = a.length - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        System.out.println("low " + low + ", high " + high + ", mid " + mid);
        if (a[mid] == target)
        {
            return mid;
        }
        else if (a[mid] < target)
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return -1;
}
Output
low 0, high 6, mid 3
low 0, high 2, mid 1
low 2, high 2, mid 2
-1
  1. 1Step 1. 21 > 20, so high = 2.
  2. 2Step 2. mid = 1; 8 < 20, so low = 2.
  3. 3Step 3. mid = 2; 15 < 20, so low = 3. Now low > high: every element has been eliminated, and the method returns −1.
Result: The output shows three ranges and then -1. Binary search ends when the value is found or all elements have been eliminated.
Common Mistake 4 · Stopping When low Equals high

A loop condition of low < high stops while one element remains unchecked, so a target in that position is reported missing. The condition must be low <= high.

6Binary Search Versus Linear Search

Binary search is typically more efficient than linear search. A linear search may examine every element, so 1,000 elements can take 1,000 checks. A binary search halves the remaining range each step, so 1,000 elements take about 10 checks, and 1,000,000 elements about 20. Doubling the amount of data adds only one step.

The trade-off is the requirement of sorted data. For a small or unsorted collection, or one that is searched only once, a linear search is simple and correct. For a large sorted collection searched many times, binary search is far faster.

Figure 4. Because each step eliminates half of the remaining elements, the number of steps grows very slowly as the data grows.
Linear searchBinary search
Data must be sorted?NoYes
Where it startsOne endThe middle
Eliminated per stepOne elementHalf of the remaining elements
Worst case, 1,000 elements1,000 checksAbout 10 checks
Worst case, 1,000,000 elements1,000,000 checksAbout 20 checks
Worked Example 6 Efficiency

Counting Steps on 1,000 Elements

Count how many elements each search examines to find the last value in a sorted array of 1,000 elements.

Code
public static int linearSteps(int[] a, int target)
{
    int steps = 0;
    for (int i = 0; i < a.length; i++)
    {
        steps++;
        if (a[i] == target)
        {
            return steps;
        }
    }
    return steps;
}

public static int binarySteps(int[] a, int target)
{
    int steps = 0;
    int low = 0;
    int high = a.length - 1;
    while (low <= high)
    {
        steps++;
        int mid = (low + high) / 2;
        if (a[mid] == target)
        {
            return steps;
        }
        else if (a[mid] < target)
        {
            low = mid + 1;
        }
        else
        {
            high = mid - 1;
        }
    }
    return steps;
}
Output
linear 1000, binary 10
  1. 1The array holds 0, 2, 4, …, 1998, sorted, with 1998 last.
  2. 2Linear search examines every element before reaching the last one: 1,000.
  3. 3Binary search halves the range each step: 1,000, 500, 250, … reaches the target in 10 steps.
Result: The output is linear 1000, binary 10. Binary search is typically more efficient than linear search, and the advantage grows with the size of the data.
Worked Example 7 Halving

Watching the Range Shrink

Print how many elements remain before each step of a search for a value larger than all 64 elements.

Code
int[] a = new int[64];
for (int i = 0; i < a.length; i++)
{
    a[i] = i;
}
int low = 0;
int high = a.length - 1;
String sizes = "";
while (low <= high)
{
    sizes += " " + (high - low + 1);
    int mid = (low + high) / 2;
    if (a[mid] < 100)
    {
        low = mid + 1;
    }
    else
    {
        high = mid - 1;
    }
}
System.out.println(sizes.substring(1));
Output
64 32 16 8 4 2 1
  1. 1Every step keeps the right half, because every element is less than 100.
  2. 2The range halves from 64 to 1, then empties, so the search ends after 7 steps (Figure 4).
Result: The output is 64 32 16 8 4 2 1. Doubling the number of elements adds only one more step to a binary search.

Four Habits for Binary Search

1. Confirm Sorted Order

Otherwise use linear search.

2. mid Rounds Down

(low + high) / 2 with integer division.

3. Exclude mid

mid + 1 or mid − 1, never mid.

4. low <= high

Stop only when the range is empty.

Core Synthesis

Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each step until the desired value is found or all elements have been eliminated. Binary search is typically more efficient than linear search. The binary search algorithm can be written either iteratively or recursively.