Selection sort takes a different approach from bubble sort. Instead of bubbling items towards the end one swap at a time, it selects the smallest (or largest) unsorted item and moves it directly to its correct position. The list is divided into two parts: a sorted section at the front and an unsorted section at the back.
How Selection Sort Works
Start with [5, 3, 8, 1, 4] and sort ascending.
Round 1: Scan the whole list for the minimum → 1 at index 3. Swap with index 0:
[1, 3, 8, 5, 4] — position 0 is now sorted.
Round 2: Scan from index 1 onwards for the minimum → 3 at index 1. Already in place.
[1, 3, 8, 5, 4] — positions 0–1 are sorted.
Round 3: Scan from index 2 → minimum is 4 at index 4. Swap with index 2:
[1, 3, 4, 5, 8] — positions 0–2 are sorted.
Round 4: Scan from index 3 → minimum is 5 at index 3. Already in place.
[1, 3, 4, 5, 8] — sorted!
Python Implementation
def selection_sort(items):
n = len(items)
for i in range(n - 1):
# Find the index of the minimum in the unsorted part
min_index = i
for j in range(i + 1, n):
if items[j] < items[min_index]:
min_index = j
# Swap the minimum into position i
if min_index != i:
items[i], items[min_index] = items[min_index], items[i]
return items
numbers = [5, 3, 8, 1, 4]
print(selection_sort(numbers)) # [1, 3, 4, 5, 8]
Notice that selection sort only ever swaps once per round — it finds the best swap (minimum element) and does it in one move. Bubble sort can make many swaps per pass. This makes selection sort perform fewer swaps, which is useful when swapping items is costly.
Tracing Through the Algorithm
| Round | Sorted so far | Unsorted | Min found | Swap |
|---|---|---|---|---|
| 1 | [] | [5,3,8,1,4] | 1 at idx 3 | Yes |
| 2 | [1] | [3,8,5,4] | 3 at idx 1 | No |
| 3 | [1,3] | [8,5,4] | 4 at idx 4 | Yes |
| 4 | [1,3,4] | [5,8] | 5 at idx 3 | No |
After 4 rounds, the full list is sorted.
Comparison Count
Like bubble sort, selection sort always makes exactly n(n-1)/2 comparisons regardless of the input — whether the data is nearly sorted or completely backwards, it still checks every pair. This gives it O(n²) time complexity.
| List size | Comparisons |
|---|---|
| 5 | 10 |
| 10 | 45 |
| 100 | 4,950 |
Selection sort performs the same number of comparisons whether the input is already sorted or completely random. This is different from bubble sort's optimised version, which can detect an already-sorted list and finish in just one pass.
When tracing selection sort by hand, underline or circle the sorted portion as you go. This helps you keep track of which section of the list is still being searched.
Practice Problems
Trace selection sort on [7, 2, 5, 1, 6]. Show the list after each round.
Show answer
What is the key difference between how selection sort and bubble sort decide which items to swap?