AlgoPlusAlgoPlus
Learn/Data Structures & Algorithms
Lesson

Selection Sort

Scan the unsorted region for the minimum, swap it to the boundary, and grow the sorted prefix one item at a time.

7 min read Watch it move Build it

Selection sort grows a sorted region from the left. Each pass scans the entire unsorted region, finds the smallest value, and swaps it into the first unsorted slot. It does a lot of *looking* but very little *moving* — exactly one swap per pass — which is its one redeeming quality.

Find the minimum, place it, repeat

  1. 1Set the boundary at index 0 — everything left of it is sorted, everything from it rightward is not.
  2. 2Scan the unsorted region to find the index of its minimum.
  3. 3Swap that minimum into the boundary position.
  4. 4Move the boundary right by one and repeat until only one element remains.
Few swaps is the whole point
Selection sort makes at most n − 1 swaps total, no matter the input. When moving an item is far more expensive than comparing two (large records, costly writes), that minimal write count can make it the right choice despite being O(n²).
function selectionSort(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    let min = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[min]) min = j; // track the smallest
    }
    if (min !== i) [arr[i], arr[min]] = [arr[min], arr[i]];
  }
  return arr;
}
Not adaptive, and not stable
It always scans the full remaining region, so a sorted input is no faster — selection sort is not adaptive. And a long-distance swap can jump one value past an equal twin, so it is unstable.
OperationTimeSpace
Comparisons · same scan on every inputO(n²)O(1)
Swaps · at most n − 1 — its one virtueO(n)O(1)
Check yourself
How does selection sort differ from bubble sort in how it moves data?