Selection Sort

Divides the array into a sorted prefix and unsorted suffix, repeatedly selecting the minimum from the suffix and appending it to the prefix.

Syntax

selectionSort(arr)

Parameters

NameTypeRequiredDescription
arr Array<number> Yes The mutable array of numbers to sort in-place.

Returns

void — Sorts the input array in-place; returns nothing.

Examples

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

const nums = [64, 25, 12, 22, 11];
selectionSort(nums);
console.log(nums);
Output
[ 11, 12, 22, 25, 64 ]
// Edge case: single element
function selectionSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let minIdx = i;
    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIdx]) minIdx = j;
    }
    if (minIdx !== i) {
      [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];
    }
  }
}

const single = [42];
selectionSort(single);
console.log(single);
Output
[ 42 ]

Notes

| Case | Time | Space | |---------|--------|-------| | Best | O(n²) | O(1) | | Average | O(n²) | O(1) | | Worst | O(n²) | O(1) | Selection sort always performs exactly n*(n-1)/2 comparisons regardless of input order, making it unsuitable for large or nearly-sorted arrays. It is **not** stable in its basic form (a swap can move equal elements out of order). One advantage: it makes at most O(n) swaps, useful when writes are expensive (e.g. flash storage).

See also