Algorithms · Visualized
Selection Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Selection Sort divides the array into a sorted part (at the front) and an unsorted part (the rest). Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Selection Sort
SortingSelection Sort divides the array into a sorted part (at the front) and an unsorted part (the rest). On every pass, it scans the unsorted part to find the smallest element and swaps it into the next open slot of the sorted part.
How Selection Sort Works
- Assume the first element is the current minimum.
- Scan the rest of the array to find the actual smallest element.
- Swap that smallest element with the first unsorted position.
- Move the boundary between sorted and unsorted forward by one.
- Repeat until the entire array is sorted.
Selection Sort Worked Example
Input: [29, 10, 14, 37, 13]
Pass 1: smallest in [29,10,14,37,13] is 10 → swap with position 0 → [10,29,14,37,13]. Pass 2: smallest in [29,14,37,13] is 13 → swap → [10,13,14,37,29]. Pass 3: smallest in [14,37,29] is 14, already in place. Pass 4: smallest in [37,29] is 29 → swap → [10,13,14,29,37]. Sorted.
def selection_sort(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Selection Sort Time & Space Complexity
When to Use Selection Sort
- Situations where the cost of swapping is high but comparisons are cheap, since it does at most n swaps.
- Small arrays or teaching how a 'find the minimum' strategy builds a sorted list.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.