AP Computer Science A · Study guide

Iterative Sorting Algorithms

AP® Computer Science A · Data Collections

Iterative Sorting Algorithms

Selection sort and insertion sort for arrays and ArrayLists: the sorted and unsorted portions, what each pass does, tracing the result of every step, final versus not-yet-final positions, and how much work each algorithm does.

Big Picture

Selection sort and insertion sort are iterative sorting algorithms that can be used to sort the elements in an array or ArrayList. Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct and final position in the sorted portion. Insertion sort inserts an element from the unsorted portion into its correct, but not necessarily final, position in the sorted portion by shifting elements of the sorted portion to make room for the new element.

1Sorted and Unsorted Portions

Both algorithms divide the list into two parts: a sorted portion at the front, which starts empty or with one element, and an unsorted portion holding everything else. Each pass of the outer loop moves one element from the unsorted portion into the sorted portion, so after enough passes the unsorted portion is gone and the whole list is in order.

The two algorithms differ in which element they move and how they place it. Selection sort searches the unsorted portion for the element that belongs next. Insertion sort simply takes the next element in line and finds where it fits among the elements already sorted. Tracing either algorithm means tracking the boundary between the two portions, the element being moved, and the array after each pass.

Selection sortInsertion sort
Each passSelects the smallest (or largest) unsorted element and swaps it into placeInserts the next unsorted element into the sorted portion
How elements moveOne swap per passLarger sorted elements shift right, one at a time
Position after a passCorrect and finalCorrect, but not necessarily final
Passes for n elementsn − 1n − 1
ComparisonsThe same for any dataFew for nearly sorted data; most for reversed data

2Selection Sort

Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct and final position in the sorted portion of the list. On pass i, an inner loop scans indices i + 1 through the end, remembering the index of the smallest element seen. After the scan, one swap exchanges that element with the element at index i, the first position of the unsorted portion.

The swapped-in element is the smallest of everything that remains, so no later element can ever belong before it: its position is final. An array of n elements needs n − 1 passes, because when only one element remains unsorted, it must already be the largest. Sometimes the smallest element is already in place, and the "swap" exchanges an element with itself, which changes nothing.

Figure 1. Each pass of selection sort scans the unsorted portion for its smallest element, then makes one swap.
PassUnsorted portionSmallestSwapArray afterward
129 10 14 37 1310 (index 1)a[0] ↔ a[1]10 29 14 37 13
229 14 37 1313 (index 4)a[1] ↔ a[4]10 13 14 37 29
314 37 2914 (index 2)a[2] ↔ a[2]10 13 14 37 29
437 2929 (index 4)a[3] ↔ a[4]10 13 14 29 37
Worked Example 1 Selection sort

Tracing Every Pass

The method prints the array after each pass. Predict the output.

Code
public static String show(int[] a)
{
    String s = "";
    for (int v : a)
    {
        s += " " + v;
    }
    return s.substring(1);
}

public static void selectionSort(int[] a)
{
    for (int i = 0; i < a.length - 1; i++)
    {
        int minIndex = i;
        for (int j = i + 1; j < a.length; j++)
        {
            if (a[j] < a[minIndex])
            {
                minIndex = j;
            }
        }
        int temp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = temp;
        System.out.println(show(a));
    }
}
Output
10 29 14 37 13
10 13 14 37 29
10 13 14 37 29
10 13 14 29 37
  1. 1Pass 1 (i = 0). The smallest of all five is 10, at index 1; swap it with 29.
  2. 2Pass 2 (i = 1). The smallest of 29, 14, 37, 13 is 13; swap it with 29.
  3. 3Pass 3 (i = 2). The smallest of 14, 37, 29 is 14, already at index 2; it swaps with itself.
  4. 4Pass 4 (i = 3). 29 is smaller than 37; swap. Four passes sort five elements.
Result: The output shows the four passes ending in 10 13 14 29 37. Selection sort fixes one more position each pass, so an array of n elements needs n − 1 passes.
Common Mistake 1 · Swapping With the Wrong Index

The swap at the end of each pass exchanges a[i] with a[minIndex], not with a[j]. Also, minIndex must be reset to i at the start of every pass; carrying it over from the previous pass can point into the sorted portion.

Figure 2. Selection sort repeatedly selects the smallest element of the unsorted portion and swaps it into its final position at the end of the sorted portion.
Worked Example 2 Descending order

Selecting the Largest Instead

Change one comparison to sort from largest to smallest.

Code
public static String show(int[] a)
{
    String s = "";
    for (int v : a)
    {
        s += " " + v;
    }
    return s.substring(1);
}

public static void sortDescending(int[] a)
{
    for (int i = 0; i < a.length - 1; i++)
    {
        int maxIndex = i;
        for (int j = i + 1; j < a.length; j++)
        {
            if (a[j] > a[maxIndex])
            {
                maxIndex = j;
            }
        }
        int temp = a[i];
        a[i] = a[maxIndex];
        a[maxIndex] = temp;
    }
}
Output
37 29 14 13 10
  1. 1Select the largest remaining element each pass by using >.
  2. 2Everything else is unchanged: the swap still moves it to the front of the unsorted portion.
Result: The output is 37 29 14 13 10. Selection sort can select the smallest or the largest element, giving ascending or descending order.

3Insertion Sort

Insertion sort inserts an element from the unsorted portion of a list into its correct position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element. On pass i, the element at index i is saved in a variable, often called the key. Moving left from i - 1, every sorted element larger than the key is copied one place to the right. When a smaller or equal element is reached, or the front of the list, the key is stored in the gap.

Saving the key first is essential, because the first shift overwrites index i. The loop condition must also test j >= 0 before reading a[j], so that a key smaller than every sorted element stops at the front instead of reading index −1.

Figure 3. Each pass of insertion sort saves the next element, shifts larger elements of the sorted portion one place right, and places the saved element in the gap.
PassKeyElements shifted rightArray afterward
1102910 29 14 37 13
2142910 14 29 37 13
337none10 14 29 37 13
41337, 29, 1410 13 14 29 37
Worked Example 3 Insertion sort

Tracing Every Pass

The same data, sorted by insertion. Predict the output.

Code
public static String show(int[] a)
{
    String s = "";
    for (int v : a)
    {
        s += " " + v;
    }
    return s.substring(1);
}

public static void insertionSort(int[] a)
{
    for (int i = 1; i < a.length; i++)
    {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key)
        {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
        System.out.println(show(a));
    }
}
Output
10 29 14 37 13
10 14 29 37 13
10 14 29 37 13
10 13 14 29 37
  1. 1Pass 1 (key 10). 29 is larger, so it shifts right; 10 goes to index 0.
  2. 2Pass 2 (key 14). 29 shifts right; 10 is not larger, so 14 goes to index 1.
  3. 3Pass 3 (key 37). Nothing before it is larger: no shifts.
  4. 4Pass 4 (key 13). 37, 29, and 14 shift right; 13 goes to index 1 (Figure 3).
Result: The output shows the four passes ending in 10 13 14 29 37. After pass 2, 29 sat at index 2, yet it moved again in pass 4: insertion sort positions are correct for the sorted portion but not necessarily final.
Worked Example 4 Order of conditions

Checking a[j] Before j

The loop condition below is written in the wrong order. What happens?

Code
int[] a = {29, 10};
for (int i = 1; i < a.length; i++)
{
    int key = a[i];
    int j = i - 1;
    while (a[j] > key && j >= 0)
    {
        a[j + 1] = a[j];
        j--;
    }
    a[j + 1] = key;
}
System.out.println(a[0]);
  1. 1The key 10 is the smallest, so 29 shifts and j becomes −1.
  2. 2The next test evaluates a[-1] first, before j >= 0 can stop it, and throws an ArrayIndexOutOfBoundsException.
  3. 3The fix: while (j >= 0 && a[j] > key), so short-circuit evaluation protects the array access.
Result: The program stops with an ArrayIndexOutOfBoundsException. In insertion sort, the bounds check must come first in the loop condition.
Common Mistake 2 · Losing the Key or Testing a[j] First

If the element at index i is not saved before shifting, it is overwritten and lost. And while (a[j] > key && j >= 0) reads a[-1] when the key belongs at the front. Save the key first, and write j >= 0 first.

4Final Positions and Not-Yet-Final Positions

The most important difference for tracing is what a partially sorted list looks like. After k passes of selection sort, the first k elements are the k smallest elements of the whole list, in order, and they will never move again. After k passes of insertion sort, the first k + 1 elements are in order relative to each other, but they are simply the first k + 1 elements of the original list; a later, smaller element can still be inserted among them and push them right.

That difference is often the quickest way to identify an unknown algorithm from a trace. If the front of the list after one pass holds the smallest value of the whole list, the algorithm is probably selection sort. If it holds the first two original values in order, it is probably insertion sort.

Figure 4. Insertion sort inserts the next element of the unsorted portion into its correct, but not necessarily final, position in the sorted portion by shifting larger elements right.
Worked Example 5 Partial traces

After Two Passes of Each

Run only the first two passes of each algorithm on the same data. Predict both arrays.

Code
public static String show(int[] a)
{
    String s = "";
    for (int v : a)
    {
        s += " " + v;
    }
    return s.substring(1);
}

public static void selectionPasses(int[] a, int passes)
{
    for (int i = 0; i < passes; i++)
    {
        int minIndex = i;
        for (int j = i + 1; j < a.length; j++)
        {
            if (a[j] < a[minIndex])
            {
                minIndex = j;
            }
        }
        int temp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = temp;
    }
}

public static void insertionPasses(int[] a, int passes)
{
    for (int i = 1; i <= passes; i++)
    {
        int key = a[i];
        int j = i - 1;
        while (j >= 0 && a[j] > key)
        {
            a[j + 1] = a[j];
            j--;
        }
        a[j + 1] = key;
    }
}
Output
1 3 6 8 5
3 6 8 1 5
  1. 1Selection: pass 1 brings the overall smallest, 1, to the front; pass 2 finds 3 already in place. The first two elements are the two smallest of the whole array.
  2. 2Insertion: pass 1 sorts 8 and 3; pass 2 inserts 6 between them. The first three elements are sorted among themselves but are not yet the three smallest.
Result: The output is 1 3 6 8 5 and 3 6 8 1 5. After k passes, selection sort's first k elements are final; insertion sort's first k + 1 elements are only sorted relative to each other.
Common Mistake 3 · Treating Insertion Sort Positions as Final

Insertion sort places each key in its correct position within the sorted portion. That position is not necessarily final: in the trace above, 29 was at index 1 after pass 1 and at index 3 at the end. Only selection sort fixes elements in their final positions pass by pass.

5Sorting ArrayList Objects

Both algorithms can be used to sort the elements of an ArrayList. The logic is the same; the syntax changes to get, set, and size(). Strings are compared with compareTo, which returns a negative number when the first string comes earlier, so a.compareTo(b) < 0 plays the role of a < b.

Insertion sort fits an ArrayList especially well: removing the key with remove(i) and inserting it with add(j + 1, key) lets the list do the shifting. Selection sort's swap uses get to read both elements and set to write them back, with a temporary variable as usual.

Worked Example 6 ArrayList of strings

Selection Sort With compareTo

Sort a list of words alphabetically.

Code
ArrayList<String> words = new ArrayList<String>();
words.add("pear");
words.add("fig");
words.add("lime");
words.add("apple");
for (int i = 0; i < words.size() - 1; i++)
{
    int minIndex = i;
    for (int j = i + 1; j < words.size(); j++)
    {
        if (words.get(j).compareTo(words.get(minIndex)) < 0)
        {
            minIndex = j;
        }
    }
    String temp = words.get(i);
    words.set(i, words.get(minIndex));
    words.set(minIndex, temp);
}
System.out.println(words);
Output
[apple, fig, lime, pear]
  1. 1compareTo replaces <: a negative result means the first string comes earlier alphabetically.
  2. 2get and set replace bracket access; the swap still uses a temporary variable.
Result: The output is [apple, fig, lime, pear]. Selection sort works the same way on an ArrayList, comparing strings with compareTo.
Worked Example 7 ArrayList of numbers

Insertion Sort With remove and add

An ArrayList can shift elements itself.

Code
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(7);
nums.add(3);
nums.add(9);
nums.add(1);
for (int i = 1; i < nums.size(); i++)
{
    int key = nums.remove(i);
    int j = i - 1;
    while (j >= 0 && nums.get(j) > key)
    {
        j--;
    }
    nums.add(j + 1, key);
    System.out.println(nums);
}
Output
[3, 7, 9, 1]
[3, 7, 9, 1]
[1, 3, 7, 9]
  1. 1Lift the key with remove(i); the list is one shorter for a moment.
  2. 2Find the gap by moving j left past every larger element.
  3. 3Drop the key with add(j + 1, key), which shifts the larger elements right automatically.
Result: The output shows [3, 7, 9, 1], [3, 7, 9, 1], then [1, 3, 7, 9]. The steps are the same as the array version; remove and add do the shifting.

6Comparing the Work

For a list of n elements, selection sort always makes the same number of comparisons: (n − 1) + (n − 2) + … + 1, because each pass scans the entire unsorted portion regardless of the data. It makes at most one swap per pass. Insertion sort's work depends on the data. On a list that is already sorted, each pass makes one comparison and no shifts. On a list in reverse order, every key travels all the way to the front, and the number of comparisons matches selection sort's.

Counting statements during a trace, such as comparisons in the inner loop or shifts in insertion sort, is the reliable way to answer questions about how many times something happens. Write down the inner loop's starting and ending values for each pass and add them up.

Worked Example 8 Counting the work

Comparisons on Sorted and Reversed Data

Count the comparisons each algorithm makes on already-sorted data and on reversed data.

Code
public static int selectionComparisons(int[] a)
{
    int count = 0;
    for (int i = 0; i < a.length - 1; i++)
    {
        int minIndex = i;
        for (int j = i + 1; j < a.length; j++)
        {
            count++;
            if (a[j] < a[minIndex])
            {
                minIndex = j;
            }
        }
        int temp = a[i];
        a[i] = a[minIndex];
        a[minIndex] = temp;
    }
    return count;
}

public static int insertionComparisons(int[] a)
{
    int count = 0;
    for (int i = 1; i < a.length; i++)
    {
        int key = a[i];
        int j = i - 1;
        boolean moving = true;
        while (j >= 0 && moving)
        {
            count++;
            if (a[j] > key)
            {
                a[j + 1] = a[j];
                j--;
            }
            else
            {
                moving = false;
            }
        }
        a[j + 1] = key;
    }
    return count;
}
Output
selection: 10 10
insertion: 4 10
  1. 1Selection sort always scans the whole unsorted portion: 4 + 3 + 2 + 1 = 10 comparisons, whatever the data.
  2. 2Insertion sort on sorted data makes one comparison per pass and never shifts: 4.
  3. 3Insertion sort on reversed data shifts every key to the front: 1 + 2 + 3 + 4 = 10.
Result: The output is selection: 10 10 and insertion: 4 10. Insertion sort does much less work when data is nearly sorted; selection sort does the same work every time.
Common Mistake 4 · Miscounting the Passes

Both algorithms make n − 1 passes over a list of n elements. Selection sort's outer loop runs while i < a.length - 1; insertion sort's runs from i = 1 while i < a.length. Check where each loop starts before counting.

Four Habits for Sorting Traces

1. Track the Boundary

Sorted portion on the left, unsorted on the right.

2. Selection: Scan, Then Swap

One swap per pass; positions final.

3. Insertion: Lift, Shift, Drop

Positions correct but not yet final.

4. Write Each Pass

The array after every pass, in a table.

Core Synthesis

Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or ArrayList. Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list. Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.