Back

Selection Sort Algorithm

Interactive Demonstration

Selection sort repeatedly finds the minimum element from the unsorted part of the array and swaps it with the first unsorted element.

50%

Generate a new array or click Sort/Step Through.

How Selection Sort Works

Steps:

  1. Find the minimum element in the unsorted part.
  2. Swap it with the first unsorted element.
  3. Mark the first unsorted element as sorted.
  4. Repeat until the entire array is sorted.

Time and Space Complexity

Time Complexity

O(n²) - Requires nested loops to iterate through the array.

Space Complexity

O(1) - Sorts in-place, requiring minimal extra memory.

Implementation

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