Algorithm Deep Dives

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.

Aman Jaiman
5 min read
On this page +
  1. In plain English
  2. How Selection Sort works
  3. Pseudocode
  4. Complexity and trade-offs
  5. Frequently asked questions

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.

Found this useful?

Share it with someone who is learning this too.

Questions

Frequently asked questions

What is the time complexity of Selection Sort? +
Selection Sort is O(n²) in best, average, and worst cases because it always scans the entire unsorted region. Its space complexity is O(1).
Why does Selection Sort make so few swaps? +
It performs exactly one swap per pass — at most n-1 total — because it finds the minimum first and moves it directly into place, unlike Bubble Sort which swaps repeatedly.
Is Selection Sort stable? +
No. Swapping the minimum into place can move an equal-valued element past its original peers, breaking relative order. A linked-list variant can be made stable.

See it in motion

Watch this algorithm and nine others run step by step, with live pseudocode and comparison counters.

Launch the visualiser
Aman Jaiman
Written by
Aman Jaiman

Software engineer at a stealth-stage startup, and previously a front-end engineer for around a year and a half.

Keep reading

Related guides

Link copied