The Efficiency of Selection Sort
Selection Sort contains two types of steps: comparisons and swaps. We compare each value with the lowest number we’ve encountered in each pass-through, and we swap the lowest number into its correct position.
Looking back at our example array that contains five elements, we had to make a total of 10 comparisons. Let’s break it down in the following table:
Pass-Through # | # of Comparisons |
|---|---|
1 | 4 comparisons |
2 | 3 comparisons |
3 | 2 comparisons |
4 | 1 comparison |
That’s a grand total of 4 + 3 + 2 + 1 = 10 comparisons.
To put it in a way that works for arrays of all sizes, we’d say that for N elements, we make
(N - 1) + (N - 2) + (N - 3) … + 1 comparisons.
As for swaps, though, we only need to make a maximum of one swap per pass-through. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access