Lesson 2 of 20

Selection Sort

Selection Sort

Selection Sort divides the array into a sorted region (left) and an unsorted region (right). Each pass finds the minimum element in the unsorted region and moves it to the end of the sorted region.

How It Works

  1. Find the minimum element in the unsorted portion arr[i..n-1].
  2. Swap it with arr[i].
  3. Advance i by one — the sorted region grows.
  4. Repeat until the entire array is sorted.
function selectionSort(arr) {
  const a = [...arr];
  for (let i = 0; i < a.length; i++) {
    let minIdx = i;
    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < a[minIdx]) minIdx = j;
    }
    [a[i], a[minIdx]] = [a[minIdx], a[i]];
  }
  return a;
}

Complexity

CaseTimeSpace
BestO(n²)O(1)
AverageO(n²)O(1)
WorstO(n²)O(1)

Unlike bubble sort, selection sort always makes exactly n-1 swaps, regardless of input order. This makes it useful when writes (swaps) are expensive.

Your Task

Implement selectionSort(arr) that returns a new array sorted in ascending order.

JavaScript loading...
Loading...
Click "Run" to execute your code.