Sorting by Selection
Selection sort follows the most direct strategy imaginable: find the smallest element and put it first; then find the smallest of the rest and put it second; and so on. It is the simple algorithm with the most predictable behavior, the one that performs the fewest exchanges, and, unlike the previous two, it is not stable.
- How direct selection works, and how to trace it.
- Why it always performs the same number of comparisons, whatever the input.
- Why it performs very few exchanges, and when that matters.
- Why it is not stable, with a concrete example.
The Idea
Direct selection consists of selecting the lowest element of the vector and exchanging it with the first element. Then the process is repeated with the remaining elements (from the second position to the end), and so on, until only one element remains: the highest of all, which is already in its place.
After step , the first positions contain the smallest elements, in their final order, as in bubble sort. The difference is how the smallest element gets there: with a single exchange, instead of a chain of adjacent exchanges.
public void sort(int[] elements) {
for (int i = 0; i < elements.length - 1; i++) {
int posMin = Util.findPosMin(elements, i); // O(n - i): scans the rest of the vector
if (i != posMin) {
Util.swap(elements, i, posMin);
}
}
}
The check i != posMin avoids exchanging an element with itself when it is already in its place. Without it, the algorithm performs exactly exchanges, some of them useless.
Trace
With the initial vector 4 5 6 1 3 2 7 8:
| Step | Minimum of the rest | Vector after the step |
|---|---|---|
| 1 | 1 | 1 5 6 4 3 2 7 8 |
| 2 | 2 | 1 2 6 4 3 5 7 8 |
| 3 | 3 | 1 2 3 4 6 5 7 8 |
| 4 | 4 | 1 2 3 4 6 5 7 8 (already in place: no exchange) |
| 5 | 5 | 1 2 3 4 5 6 7 8 |
| 6 | 6 | 1 2 3 4 5 6 7 8 (no exchange) |
| 7 | 7 | 1 2 3 4 5 6 7 8 (no exchange) |
Note how the exchanges send elements far away: in step 1, the 4 jumps from the first position to the fourth one. That is why selection sort can remove several inversions with a single exchange, and also why it is not stable.
ProofSelection sort is correctAnalysis
Comparisons: always the same
To find the minimum of the elements from position to the end, findPosMin must inspect all of them, whatever their values: there is no shortcut, since the last element could always be the smallest. With (positions 0 to 4), findPosMin starts with the element at position as the provisional minimum and compares it with every element after it:
| Step | Compared with positions | Comparisons |
|---|---|---|
| 0 | 1, 2, 3, 4 | 4 |
| 1 | 2, 3, 4 | 3 |
| 2 | 3, 4 | 2 |
| 3 | 4 | 1 |
| Total | 10 |
Each step has one element fewer to look at, because the previous step left one more element in its final place. In general, step compares the elements after position , which are , and the steps go from to (with one element left, there is nothing to do). Adding them up gives the same staircase as in bubble sort:
For : , the same as the table.
in every case: sorted, reverse or random data. Selection sort is in the best, worst and average cases, and it is not adaptive at all: sorting an already sorted vector costs exactly the same comparisons as sorting a random one.
Exchanges: very few
Each step performs at most one exchange, so there are at most exchanges: , compared with for bubble sort and insertion sort.
- Sorted data: every element is already in place, so there are 0 exchanges (thanks to the check
i != posMin). - Reverse data: each exchange puts two elements in their final positions (the smallest goes to the front and the largest goes to the back), so the second half of the steps finds everything in place. For , the vector 8 7 6 5 4 3 2 1 is sorted with just 4 exchanges: .
- Random data: almost every step needs an exchange, about in total (994 for in our measurements).
| Case | Comparisons | Exchanges | Complexity |
|---|---|---|---|
| Best (sorted) | |||
| Worst (in terms of exchanges) | |||
| Reverse order | |||
| Average (random) |
In summary: selection sort has a very high number of comparisons but a very small number of exchanges, and it is predictable: the number of comparisons depends only on . It is in place.
Minimizing exchanges is useful when writing is much more expensive than reading: for example, when sorting large records that must be physically moved (rather than references to them), or on storage technologies where each write has a high cost or wears the device out (some kinds of flash memory). In those situations, selection sort can beat algorithms that are better in terms of comparisons.
Selection Sort Is Not Stable
Because the exchange sends the element at position to a distant position, it can jump over other elements with the same key. Consider three records with keys 5a 5b 3, where the letters only distinguish the two 5s:
| Step | Action | Result |
|---|---|---|
| 1 | The minimum is 3; exchange it with the first element (5a) | 3 5b 5a |
| 2 | The minimum of 5b 5a is 5b (the first one found), already in place | 3 5b 5a |
The original order of the two 5s (5a before 5b) has been reversed: the algorithm is not stable. It can be made stable by inserting the minimum in its place and shifting the elements in between (instead of exchanging), but then it performs moves and loses its main advantage.
🧠 Checkpoint: Comparing the three simple algorithms
Question: You must sort an array of 50 records of 10 KB each, physically moving the records, and the comparisons are cheap. Which simple algorithm would you choose? And if the array has 50 integers and is almost sorted?
Answer: For the large records, selection sort: it performs at most 49 exchanges, while bubble and insertion sort could move records more than a thousand times (around moves on average, each copying 10 KB). For the almost sorted integers, insertion sort: its cost is close to linear on almost sorted data, while selection sort performs its 1,225 comparisons regardless of the input.
Measurements
Times in milliseconds, without optimization (-Xint), with the course implementation:
| Sorted | Random | Reverse | |
|---|---|---|---|
| 4,000 | 128 | 124 | 156 |
| 8,000 | 509 | 507 | 540 |
The times are almost identical in the three cases, as predicted: the number of comparisons does not depend on the input. Doubling multiplies them by about 4. Compared with the other simple algorithms for , selection sort is faster than bubble sort in every case, but much slower than insertion sort on sorted data, and slower on random data too (insertion: 329 ms).
- Expecting selection sort to profit from sorted input. It always makes comparisons.
- Swapping inside the inner loop. Find the position of the minimum first, and swap once per pass.
- Calling it stable. The long-distance swap can move an element past an equal one.
Summary
- Selection sort selects the minimum of the remaining elements and exchanges it with the first of them.
- It always performs comparisons: in all cases. It is predictable and not adaptive.
- It performs at most exchanges, the fewest among the simple algorithms. That makes it interesting when moving elements is very expensive.
- It is in place but not stable.
Practice
- ✍️ Trace it. Sort 5 6 1 3 9 8 7 4 2 by hand with direct selection, writing the vector after each step and marking the steps without an exchange.
- 🔄 Selecting the maximum. Write a version that selects the largest element in each step and places it at the end of the unsorted part (you will need a method that finds the position of the maximum, similar to
findPosMin). Do its comparisons and exchanges change? - ⚖️ Both at once. Write a version that finds both the minimum and the maximum in each pass, placing them at both ends. How many passes does it need? Does the number of comparisons change?
- 💻 Measure. Implement the measurement class for selection sort and fill in the corresponding table of lab session 2. Do the three cases take the same time, as predicted?
- 🧪 Stability. Write a stress test that sorts pairs (key, original position) with selection sort and checks whether equal keys keep their original order. How often does it fail with random keys between 0 and 9?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.