Selection Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Selection Sort
Find the smallest element in the unsorted region, swap it to the front, and shrink the region. Minimum writes among the simple sorts.
How it works
Selection Sort walks the array k − 1 times. Each pass scans the entire unsorted suffix to find the minimum value, then makes a single swap to put it in its correct final position.
- Set
i = 0. - Scan
arr[i..n-1]to find the indexminof the smallest value. - Swap
arr[i]andarr[min]. - Increment
iand repeat.
The defining property: at most n − 1 swaps total. This makes Selection Sort attractive when writes are expensive (e.g., flash memory) even though it still does Θ(n²) comparisons.
Complexity
Interactive visualization
Pseudocode
procedure selectionSort(A): n ← length(A) for i from 0 to n − 2: min ← i for j from i + 1 to n − 1: if A[j] < A[min]: min ← j swap A[i], A[min]
JavaScript implementation
function selectionSort(arr) { const n = arr.length; for (let i = 0; i < n - 1; i++) { let min = i; for (let j = i + 1; j < n; j++) { if (arr[j] < arr[min]) min = j; } if (min !== i) [arr[i], arr[min]] = [arr[min], arr[i]]; } return arr; }
Pros and cons
Pros
- Minimal number of swaps — at most n − 1.
- Predictable: always Θ(n²) comparisons, no input-dependent surprises.
- In-place, O(1) extra memory.
- Conceptually simple to teach.
Cons
- Quadratic comparisons even on already-sorted input.
- Not stable in standard swap form.
- Slower than Insertion Sort on real workloads despite fewer writes.
When to use it
- Flash storage / EEPROM where write count matters more than comparisons.
- Teaching the concept of an "unsorted region" that shrinks each iteration.
- Very small arrays where simplicity beats sophistication.
Related reading
Sleep Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A unique concurrency-based sorting algorithm: spawns a separate thread for each element, sleeping for a duration proportional to the element value before writing it to the output.
By Md. Harun-Or-Roshid
Cube Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A parallel dimension sorting algorithm: organizes elements in a 3D coordinate cube and sorts vectors along the height, width, and depth axes sequentially to achieve sorted order.
By Md. Harun-Or-Roshid
Patience Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A card-game inspired sorting algorithm: distributes elements onto a series of piles such that each pile's top is \(\ge\) the incoming value, then performs a multi-way merge across pile tops.
By Md. Harun-Or-Roshid
Library Sort: Mechanism, Complexity Analysis & Interactive Visualizer
A gapped variation of Insertion Sort: leaves empty slots (gaps) in the array, allowing elements to be inserted in \(O(1)\) shift time on average by avoiding massive shifts.
By Md. Harun-Or-Roshid