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 18: Sorting Algorithms — Selection, Insertion and Merge Sort

Sorting puts data in order, and the exam expects you to know three sorting algorithms well enough to trace them by hand: selection sort, insertion sort, and merge sort. Each is simple to describe, but they differ in how they work and how much work they do, and the differences are exactly what tracing questions test. All three sort by repeatedly comparing and moving elements, and all three can be written with the nested loops and array skills from earlier units.

Selection sort works by repeatedly finding the smallest remaining element and swapping it into place. On the first pass it scans the whole array for the minimum and swaps it into position 0; on the second pass it scans from position 1 for the minimum of the rest and swaps it into position 1, and so on. It always makes the same number of comparisons, about n² / 2 for n elements, whatever the data look like, because it scans the unsorted part fully on every pass. It makes few swaps — one per pass — which is its one advantage, but its comparison count makes it slow for large data.

Insertion sort works like sorting a hand of cards: it takes the next unsorted element and inserts it into its correct position among the elements already sorted. For data that are already nearly sorted, it is fast, because each new element only needs to move a short distance; for data in reverse order, it is slow, because each element must move all the way across. Its worst case is also about n² / 2 comparisons, like selection sort, but its best case — data already sorted — is only about n comparisons, a single pass to confirm the order. That adaptivity makes it the best choice of the three for small or nearly sorted data.

Merge sort, which you met in the recursion unit, splits the array in half, sorts each half recursively, and merges the sorted halves. Its work grows as n log n, which is far better than n² for large data: for a million elements, n log n is about twenty million operations, while n² is a trillion. Its cost is extra space for the merging and a more complex implementation, and it is not adaptive — it does the same work whatever the data look like. In practice, the sorting methods in real libraries use variations of merge sort and its relatives, because the n log n growth wins as soon as the data are large.

A worked example

Worked example: trace selection sort on [5, 2, 8, 1]. Pass one scans all four elements, finds the minimum 1, and swaps it into position 0, giving [1, 2, 8, 5]. Pass two scans from position 1, finds the minimum 2 already in place, giving [1, 2, 8, 5]. Pass three scans from position 2, finds the minimum 5, and swaps it into position 2, giving [1, 2, 5, 8]. Three passes, and the array is sorted. Insertion sort on the same array would take 5, insert it before 2, then 8, then move 1 to the front, reaching the same result by a different route.

public void selectionSort(int[] data)
{
    for (int i = 0; i < data.length - 1; i++)
    {
        int minIndex = i;
        for (int j = i + 1; j < data.length; j++)
        {
            if (data[j] < data[minIndex])
            {
                minIndex = j;
            }
        }
        int temp = data[i];
        data[i] = data[minIndex];
        data[minIndex] = temp;
    }
}

The outer loop marks the boundary between the sorted front and the unsorted rest, the inner loop finds the minimum of the rest, and the swap moves it across the boundary. Note the outer bound, data.length − 1: after the second-to-last element is placed, the last one must already be the largest, so no final pass is needed. When you trace a sort, write the array after each pass, and mark the sorted part — the picture makes the algorithm's progress visible.

Key Terms

Selection sort
Sorting by repeatedly finding the minimum of the unsorted part and swapping it into place.
Insertion sort
Sorting by inserting each new element into its correct position among the sorted part.
Merge sort
Sorting by recursively sorting halves and merging them; work grows as n log n.
Swap
Exchanging two elements using a temporary variable.
Adaptive
An algorithm, like insertion sort, that runs faster on data that are already nearly sorted.

Discussion Questions

  1. Why does selection sort make the same number of comparisons whatever the data look like?
  2. For data that are already sorted, which of the three sorts is fastest, and why?
  3. Why is merge sort better than selection sort for large data?

Practice Questions

  1. Selection sort on [3, 1, 2]: what is the array after the first pass?
  2. How many swaps does selection sort make for n elements?
  3. Insertion sort on already sorted data of n elements: roughly how many comparisons?
  4. Merge sort on 8 elements: how many levels of splitting are there?
  5. Which sort would you choose for a small list that is nearly sorted?
Show answers
  1. [1, 3, 2], after swapping the minimum 1 into position 0.
  2. At most n − 1, one per pass.
  3. About n, one per element to confirm it is already in place.
  4. Three, since 8 halves to 4, then 2, then 1.
  5. Insertion sort, because it is adaptive and fast on nearly sorted data.
Keep reading to complete this lesson