Selection Sort Explained
Selection Sort repeatedly finds the minimum and places it at the front. Learn how it works, its O(n²) complexity, why it minimizes swaps, and its pseudocode.
On this page +
Selection Sort builds the sorted array one element at a time by repeatedly selecting the smallest remaining element and moving it into place. Its defining feature is that it makes at most n-1 swaps — fewer than any other simple sort — which matters when writing to memory is expensive.
How Selection Sort works #
Divide the array into a sorted region (initially empty) on the left and an unsorted region on the right. Scan the unsorted region to find the minimum, then swap it with the first unsorted element. The sorted region grows by one each pass until the whole array is ordered.
Pseudocode #
for i from 0 to n-1:
min = i
for j from i+1 to n-1:
if a[j] < a[min]:
min = j
swap(a[i], a[min])Complexity and trade-offs #
Selection Sort is O(n²) in all cases — it is not adaptive, so it does the same work even on sorted input. Its advantage is exactly n-1 swaps total, the minimum possible, making it useful when writes are costly (such as flash memory). It uses O(1) space but is not stable because swapping distant elements can reorder equal keys. Compare it with Insertion Sort in our head-to-head guide.
Frequently asked questions
What is the time complexity of Selection Sort? +
Why does Selection Sort make so few swaps? +
Is Selection Sort stable? +
See it in motion
Watch this algorithm and nine others run step by step, with live pseudocode and comparison counters.
Launch the visualiser
Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.