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.
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 sort | Insertion sort | |
|---|---|---|
| Each pass | Selects the smallest (or largest) unsorted element and swaps it into place | Inserts the next unsorted element into the sorted portion |
| How elements move | One swap per pass | Larger sorted elements shift right, one at a time |
| Position after a pass | Correct and final | Correct, but not necessarily final |
| Passes for n elements | n − 1 | n − 1 |
| Comparisons | The same for any data | Few 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.
| Pass | Unsorted portion | Smallest | Swap | Array afterward |
|---|---|---|---|---|
| 1 | 29 10 14 37 13 | 10 (index 1) | a[0] ↔ a[1] | 10 29 14 37 13 |
| 2 | 29 14 37 13 | 13 (index 4) | a[1] ↔ a[4] | 10 13 14 37 29 |
| 3 | 14 37 29 | 14 (index 2) | a[2] ↔ a[2] | 10 13 14 37 29 |
| 4 | 37 29 | 29 (index 4) | a[3] ↔ a[4] | 10 13 14 29 37 |
Tracing Every Pass
The method prints the array after each pass. Predict the output.
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));
}
}
10 29 14 37 13
10 13 14 37 29
10 13 14 37 29
10 13 14 29 37
- 1Pass 1 (i = 0). The smallest of all five is 10, at index 1; swap it with 29.
- 2Pass 2 (i = 1). The smallest of 29, 14, 37, 13 is 13; swap it with 29.
- 3Pass 3 (i = 2). The smallest of 14, 37, 29 is 14, already at index 2; it swaps with itself.
- 4Pass 4 (i = 3). 29 is smaller than 37; swap. Four passes sort five elements.
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.
Selecting the Largest Instead
Change one comparison to sort from largest to smallest.
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;
}
}
37 29 14 13 10
- 1Select the largest remaining element each pass by using
>. - 2Everything else is unchanged: the swap still moves it to the front of the unsorted portion.
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.
| Pass | Key | Elements shifted right | Array afterward |
|---|---|---|---|
| 1 | 10 | 29 | 10 29 14 37 13 |
| 2 | 14 | 29 | 10 14 29 37 13 |
| 3 | 37 | none | 10 14 29 37 13 |
| 4 | 13 | 37, 29, 14 | 10 13 14 29 37 |
Tracing Every Pass
The same data, sorted by insertion. Predict the output.
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));
}
}
10 29 14 37 13
10 14 29 37 13
10 14 29 37 13
10 13 14 29 37
- 1Pass 1 (key 10). 29 is larger, so it shifts right; 10 goes to index 0.
- 2Pass 2 (key 14). 29 shifts right; 10 is not larger, so 14 goes to index 1.
- 3Pass 3 (key 37). Nothing before it is larger: no shifts.
- 4Pass 4 (key 13). 37, 29, and 14 shift right; 13 goes to index 1 (Figure 3).
Checking a[j] Before j
The loop condition below is written in the wrong order. What happens?
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]);
- 1The key 10 is the smallest, so 29 shifts and
jbecomes −1. - 2The next test evaluates
a[-1]first, beforej >= 0can stop it, and throws anArrayIndexOutOfBoundsException. - 3The fix:
while (j >= 0 && a[j] > key), so short-circuit evaluation protects the array access.
ArrayIndexOutOfBoundsException. In insertion sort, the bounds check must come first in the loop condition.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.
After Two Passes of Each
Run only the first two passes of each algorithm on the same data. Predict both arrays.
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;
}
}
1 3 6 8 5
3 6 8 1 5
- 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.
- 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.
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.
Selection Sort With compareTo
Sort a list of words alphabetically.
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);
[apple, fig, lime, pear]
- 1
compareToreplaces<: a negative result means the first string comes earlier alphabetically. - 2
getandsetreplace bracket access; the swap still uses a temporary variable.
compareTo.Insertion Sort With remove and add
An ArrayList can shift elements itself.
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);
}
[3, 7, 9, 1]
[3, 7, 9, 1]
[1, 3, 7, 9]
- 1Lift the key with
remove(i); the list is one shorter for a moment. - 2Find the gap by moving
jleft past every larger element. - 3Drop the key with
add(j + 1, key), which shifts the larger elements right automatically.
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.
Comparisons on Sorted and Reversed Data
Count the comparisons each algorithm makes on already-sorted data and on reversed data.
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;
}
selection: 10 10
insertion: 4 10
- 1Selection sort always scans the whole unsorted portion: 4 + 3 + 2 + 1 = 10 comparisons, whatever the data.
- 2Insertion sort on sorted data makes one comparison per pass and never shifts: 4.
- 3Insertion sort on reversed data shifts every key to the front: 1 + 2 + 3 + 4 = 10.
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.
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.