Skip to main content
← All posts

Selection Sort: Mechanism, Complexity Analysis & Interactive Visualizer

Md. Harun-Or-RoshidNov 5, 20268 min readArticle
Selection Sort: Mechanism, Complexity Analysis & Interactive Visualizer
Basic Sorting · Article 3 of 62

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.

  1. Set i = 0.
  2. Scan arr[i..n-1] to find the index min of the smallest value.
  3. Swap arr[i] and arr[min].
  4. Increment i and 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

Best time
O(n²)
Average time
O(n²)
Worst time
O(n²)
Extra space
O(1)
Stable
No
In-place
Yes
Selection Sort is not stable in its standard swap form — moving the chosen min across a tie can reorder equal keys. A "shift" variant (or working with linked lists) restores stability.

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.
Up next: Insertion Sort — a clever twist that uses binary search to find the insertion point instead of scanning linearly.
Share:
Share on X
Share on LinkedIn
Share on Facebook
Share on Reddit
Share on WhatsApp
Share on Telegram
Copy link

Related reading

Selection Sort Sorting Algorithm & Guide | Draftsbook · Draftsbook