Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

AP Computer Science A: Deep Dive and FRQ Mastery — Alpha School

Lesson 16: Recursion in Practice — Binary Search and Merge Sort

Recursion earns its place in this course through two algorithms that are hard to write well any other way: binary search and merge sort. Both work by halving a problem again and again, and both are naturally recursive, because each step produces a smaller version of the same task. Understanding them is not just about the code — it is about the idea of divide and conquer, splitting a problem into halves, solving each half, and combining the answers, which is one of the most powerful patterns in computer science.

Binary search finds a value in a sorted array by comparing the target with the middle element: if the target is smaller, it searches the left half; if larger, the right half; if equal, it has found it. Each step halves the remaining data, so a binary search of a million elements needs at most about twenty comparisons, while a linear search could need a million. The method needs the array to be sorted — without that, halving is meaningless — and it needs careful index arithmetic: the middle index is (low + high) / 2, and the halves are searched with low and high adjusted by one, so the middle element is never checked twice and the search always makes progress.

Merge sort sorts an array by splitting it into halves, sorting each half recursively, and then merging the two sorted halves into one sorted result. The base case is an array of one element, which is already sorted, and the merge step walks through both halves with two pointers, always taking the smaller next element. Merge sort is stable and predictable, and it is the sorting algorithm most often asked about in tracing questions, because its recursion tree is easy to draw and its merge step is easy to follow by hand. It needs extra space for the merging, which is its main cost.

Tracing recursive algorithms means following the calls, and the best tool is a small diagram. For binary search, write down low, high, and mid at each step, and mark the half that survives. For merge sort, draw the splitting tree down to single elements, then work back up, writing the merged result at each level. The most common errors are an off-by-one in the halving, which makes the search loop forever or miss the target, and a merge that forgets to copy the leftover elements of one half when the other runs out. Check the boundaries of every half explicitly.

Merge sort's main cost is the extra space it needs while merging: the merge step builds a new array to hold the combined result, so the algorithm uses additional memory proportional to the size of the data. It also does the same amount of work whatever the input looks like, because it always splits and merges the full array, so it gains nothing from data that are already sorted. Those costs are acceptable when the data are large and the n log n growth matters, which is why merge sort and its relatives are used in practice. For small arrays, the simpler sorts are often faster in practice, because they have less overhead per step, and the difference in growth only shows up as the data grow.

A worked example

Worked example: binary search for 7 in the sorted array [2, 4, 7, 9, 12, 15]. The middle index is (0 + 5) / 2 = 2, and the element there is 7, so the search finds it in a single comparison. Searching for 12 instead: the middle is 7, which is less than 12, so the search continues in the right half, indices 3 to 5; the new middle is (3 + 5) / 2 = 4, holding 12, and the search ends. Two comparisons to find an element among six, where a linear search could have needed five.

public int binarySearch(int[] data, int target, int low, int high)
{
    if (low > high)
    {
        return -1; // base case: not found
    }
    int mid = (low + high) / 2;
    if (data[mid] == target)
    {
        return mid;
    }
    if (target < data[mid])
    {
        return binarySearch(data, target, low, mid - 1);
    }
    return binarySearch(data, target, mid + 1, high);
}

The base case is low > high, meaning the search range is empty and the target is absent, returning −1. Otherwise the middle element is checked, and the search recurses into the correct half with the range narrowed by one, so the range shrinks on every call and the method always terminates. Notice that the recursive calls are returned directly, so the found index propagates back up through the frames. In free-response answers, trace the indices at each call rather than the values, because the indices are what the code actually manipulates.

Key Terms

Divide and conquer
Splitting a problem into halves, solving each, and combining the results.
Binary search
Searching a sorted array by repeatedly halving the remaining range; needs sorted data.
Merge sort
Sorting by recursively sorting halves and merging the sorted halves.
Merge step
Combining two sorted halves into one sorted result by repeatedly taking the smaller next element.
Sorted data
Data in order, required for binary search to work.

Discussion Questions

  1. Why does binary search need sorted data?
  2. How many comparisons does binary search need at most for 1,000 elements?
  3. Why is merge sort's base case an array of one element?

Practice Questions

  1. Binary search looks for 5 in [1, 3, 5, 7, 9]. What is the first middle element checked?
  2. What does binary search return when the target is absent?
  3. Merge sort splits [5, 2, 8, 1] into halves. What are the two halves?
  4. Merge [2, 6] and [3, 5]. What is the merged result?
  5. Why is (low + high) / 2 the right middle index, and what happens if you forget the −1 and +1 when recursing?
Show answers
  1. 5, at index (0 + 4) / 2 = 2, so it is found immediately.
  2. −1, from the base case where the search range becomes empty.
  3. [5, 2] and [8, 1].
  4. [2, 3, 5, 6].
  5. It is the middle of the current range; without adjusting by one, the same middle element would be searched again and the method might never terminate.
Keep reading to complete this lesson