Selection Sort in Python
Learn the Selection Sort algorithm in Python! Beginner-friendly, step-by-step visual explanation with clean, runnable Python code.
Try it yourself
Run this code directly in your browser. Click "Open in full editor" to experiment further.
Click Run to see output
Or press Ctrl + Enter
How it works
Selection Sort is the algorithm you'd use if you were sorting a row of books on a shelf by hand: find the shortest one, put it on the far left, then find the next shortest, and so on. ๐
The Real-World Analogy
Imagine a row of 10 numbered cards face-up on a table. You want them sorted, smallest to largest. You scan all the cards, find the smallest, and swap it with whatever card is in position 1. Now position 1 is locked in. You scan positions 2โ10, find the smallest of those, and swap it into position 2. Repeat until you reach the end.
At every moment, the array has two regions:
[ sorted | unsorted ]The sorted region grows by one element each pass.
How It Works (Step by Step)
1. Start at index 0.
2. Look through the rest of the array and find the index of the smallest value.
3. Swap that smallest value into the current index.
4. Move to the next index and repeat โ but only scan what's still unsorted.
5. Stop when you've placed every element.
Tiny Trace โ `[5, 2, 8, 1, 9]`
Pass 1: smallest in [5,2,8,1,9] is 1 โ swap โ [1, 2, 8, 5, 9]
Pass 2: smallest in [2,8,5,9] is 2 โ already there โ [1, 2, 8, 5, 9]
Pass 3: smallest in [8,5,9] is 5 โ swap โ [1, 2, 5, 8, 9]
Pass 4: smallest in [8,9] is 8 โ already there โ [1, 2, 5, 8, 9]
Pass 5: only one element left โ done!Why Use It?
n - 1 swaps total. If writing to memory is expensive (e.g., flash storage), this matters.Time & Space Complexity
Selection Sort vs Bubble Sort vs Insertion Sort
All three are O(n^2), but they trade off differently:
| Algorithm | Best case | Swaps | Adaptive? | Stable? |
|---|---|---|---|---|
| Bubble Sort | O(n) | O(n^2) | Yes (early exit) | Yes |
| Insertion Sort | O(n) | O(n^2) | Yes (loves sorted) | Yes |
| Selection Sort | O(n^2) | O(n) | No | No |
Pick selection sort when: writes are expensive and you only care about minimizing swaps. Skip it when: the data might already be partially sorted โ insertion sort will crush it in that scenario.
A Note on Stability
Selection sort is not stable โ equal elements can have their order flipped by the long-distance swap. If you need stable sorting (e.g., sorting records by a secondary key), reach for insertion sort or merge sort instead.
Related examples
Bubble Sort in Python
Learn the Bubble Sort algorithm in Python! Step-by-step visual explanation with beginner-friendly, optimized Python code.
Insertion Sort in Python
Learn the Insertion Sort algorithm in Python! Beginner-friendly, step-by-step visual explanation with clean, runnable Python code.
Quick Sort in Python
Learn Quick Sort in Python! A beginner-friendly guide to the famous Divide and Conquer algorithm. See how pivots and partitioning make sorting blazing fast.