Selection Sort
Table of Contents + β
Say you have a row of exam papers and you want them sorted by marks, lowest first. Here is one simple way. You look at the whole pile, pick the paper with the lowest marks, and put it at the very front. Then you look at what is left. You pick the smallest from that and put it next. You keep going till nothing is left. That is exactly what selection sort does. It picks the smallest item from the unsorted part and moves it to the front, again and again.
π€ What Selection Sort Actually Does
The idea is that selection sort splits your array into two parts in your head.
- A sorted part on the left. This starts empty.
- An unsorted part on the right. This starts as the whole array.
In each round you do one job. You scan the unsorted part. You find the smallest value. Then you swap it to the front of the unsorted part. Now that value is in its final spot. So the sorted part grows by one and the unsorted part shrinks by one.
You repeat this for every position. After the last round the whole array is sorted.
Note
βSelectionβ comes from the idea that each round you select the smallest remaining value. Some people sort largest-first instead. It is the same idea, just flipped.
π A Small Trace
Let us sort [29, 10, 14, 37, 13] from small to large. Watch how the smallest value moves to the front each round.
We start with the full array unsorted. The smallest value is 10, so we swap it with the front.
Start: [29, 10, 14, 37, 13]Round 1: pick 10 -> swap with 29 -> [10, 29, 14, 37, 13]Now 10 is locked. We look at the rest [29, 14, 37, 13]. The smallest is 13, so we swap it to the front of that part.
Round 2: pick 13 -> swap with 29 -> [10, 13, 14, 37, 29]Now 10, 13 are locked. The smallest of [14, 37, 29] is 14. It is already at the front, so the swap does nothing.
Round 3: pick 14 -> already in place -> [10, 13, 14, 37, 29]Now look at [37, 29]. The smallest is 29, so we swap it.
Round 4: pick 29 -> swap with 37 -> [10, 13, 14, 29, 37]Only one value is left, so it is already sorted. We are done.
Final: [10, 13, 14, 29, 37]See the pattern? For an array of n items you do n - 1 rounds. The last item falls into place on its own.
π Steps to Sort
Here is the plain recipe before we write any code.
- Start at the first position. Call it
i. - Assume the item at
iis the smallest. Remember its index as minIndex. - Look at every item from
i + 1to the end. If you find a value smaller than the one atminIndex, updateminIndexto that position. - After the scan, swap the item at
iwith the item atminIndex. The smallest value of the unsorted part is now in place. - Move
iforward by one and repeat untilireaches the second-last position.
The inner scan is the part that finds the smallest. The outer loop just decides which position we are filling next.
π» Selection Sort in Code
Now let us turn that recipe into a real program. Each version writes a selectionSort function, calls it on the same array, and prints the result.
# Sort the list from small to largedef selection_sort(arr): n = len(arr) for i in range(n - 1): min_index = i # assume current spot holds the smallest for j in range(i + 1, n): if arr[j] < arr[min_index]: min_index = j # found a smaller value # swap the smallest found into position i arr[i], arr[min_index] = arr[min_index], arr[i]
numbers = [29, 10, 14, 37, 13]selection_sort(numbers)print(numbers)The output of the above code will be:
[10, 13, 14, 29, 37]Tip
Notice the swap happens only once per round, after the inner scan is over. Beginners often swap inside the inner loop. That still sorts, but it does many extra swaps for no reason.
β±οΈ How Fast Is It?
Let us count the work. The outer loop runs about n times. For each of those, the inner scan looks at the rest of the array. So you compare items again and again. The total comes to about n * n / 2 comparisons. We drop the constants and call that O(n^2) time.
Here is the part that surprises people. Selection sort does the same number of comparisons no matter what. Even if the array is already sorted, it still scans the whole unsorted part every round to be sure it found the smallest. So the best case is also O(n^2). It cannot finish early.
The good news is space. It sorts inside the same array. It only uses a couple of extra variables like minIndex and a temp value for the swap. That is O(1) extra space.
Caution
Selection sort is not stable. Stable means two equal values keep their original order. The long-distance swap in selection sort can jump one equal value past another and flip their order. So do not use it when the original order of equal items matters.
Here is the full picture in one table.
| Case | Time | Space |
|---|---|---|
| Best (already sorted) | O(n^2) | O(1) |
| Average | O(n^2) | O(1) |
| Worst (reverse sorted) | O(n^2) | O(1) |
One small plus point. Selection sort does at most n - 1 swaps total, one per round. So when writing to memory is very costly and reading is cheap, it can be a fair pick even with its slow compare count.
β οΈ Common Mistakes
A few slip-ups show up again and again. Watch for these.
- Running the outer loop all the way to
ninstead ofn - 1. The last item is already in place, so the extra round just wastes time. - Starting the inner loop at
iinstead ofi + 1. Comparing an item with itself does nothing useful. - Swapping inside the inner loop instead of once after it. It still works but does far more swaps than needed.
- Forgetting to reset
minIndextoiat the start of each round. If you carry over the old value, the result is wrong.
π§© What Youβve Learned
- β Selection sort splits the array into a sorted left part and an unsorted right part.
- β Each round it picks the smallest value from the unsorted part and swaps it to the front.
- β
For
nitems you runn - 1rounds, with one swap per round. - β Time is O(n^2) in every case, even when the array is already sorted.
- β It sorts in place with O(1) extra space, but it is not stable.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
In each round, what does selection sort move to the front of the unsorted part?
Why: Selection sort scans the unsorted part, finds the smallest value, and swaps it to the front.
- 2
Why is selection sort's best case still O(n^2)?
Why: It cannot finish early because it always scans the unsorted part to be sure it found the smallest value.
- 3
How much extra space does selection sort use?
Why: It sorts inside the same array and only needs a couple of extra variables, so the extra space is O(1).
- 4
How many swaps does selection sort do at most for n items?
Why: There is one swap per round and there are n - 1 rounds, so at most n - 1 swaps.