Selection Sort

Finds the minimum element from the unsorted part and puts it at the beginning. Simple but inefficient for large lists.

Best O(n²) Avg O(n²) Worst O(n²) Space O(1) Stable No In-place Yes Comparison-based

How it works

Selection Sort scans the unsorted region for the minimum element and swaps it into the next sorted position. It repeats, growing the sorted prefix by one element per pass.

It always performs the same number of comparisons regardless of input order, and at most n-1 swaps total.

Implementation

function selectionSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    let minIdx = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIdx]) minIdx = j;
    }
    [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
  }
}

Advantages

  • Minimal number of writes (at most n-1 swaps) — useful when writes are expensive.
  • Simple and in-place.

Disadvantages

  • Always O(n^2) comparisons, even on sorted input — not adaptive.
  • Not stable in its classic form.

When to use it

Use it only when the cost of writing/moving elements dominates and the array is small.