Selection Sort contains two types of steps: comparisons and swaps. That is, we compare each element with the lowest number we’ve encountered in each passthrough, and we swap the lowest number into its correct position.
Looking back at our example of an array containing five elements, we had to make a total of ten comparisons. Let’s break it down.
Passthrough # | # of comparisons |
---|---|
1 | 4 comparisons |
2 | 3 comparisons |
3 | 2 comparisons |
4 | 1 comparison |
So that’s a grand total of 4 + 3 + 2 + 1 = 10 comparisons.
To put it more generally, we’d say that for N elements, we make
(N - 1) + (N - 2) + (N - 3) … + 1 comparisons.
As for swaps, however, we only need to make a maximum of one swap per passthrough. This is because in each passthrough, we make either one or zero swaps, depending on whether the lowest number of that passthrough is already in the correct position. Contrast this with Bubble Sort, where in a worst-case scenario—an array in descending order—we have to make a swap for each and every comparison.
Here’s the side-by-side comparison between Bubble Sort and Selection Sort:
N elements | Max # of steps in Bubble Sort | Max # of steps in Selection Sort |
---|---|---|
5 | 20 | 14 (10 comparisons + 4 swaps) |
10 | 90 | 54 (45 comparisons + 9 swaps) |
20 | 380 | 199 (180 comparisons + 19 swaps) |
40 | 1560 | 819 (780 comparisons + 39 swaps) |
80 | 6320 | 3239 (3160 comparisons + 79 swaps) |
From this comparison, it’s clear that Selection Sort contains about half the number of steps that Bubble Sort does, indicating that Selection Sort is twice as fast.