Speed:
Unsorted
Comparing
Current Element
Sorted
Length:
Selection Sort
A simple in-place comparison sorting algorithm that divides the input list into two parts: a sorted sublist and an unsorted sublist.

Statistics

Iterations
0
Swaps
0

Complexity Analysis

Case
Best
Average
Worst
Time
O(n²)
O(n²)
O(n²)
Space
O(1)

How It Works

  1. Find the minimum element in the unsorted part of the array
  2. Swap it with the element at the beginning of the unsorted part
  3. Move the boundary between the sorted and unsorted parts one element to the right
  4. Repeat until the entire array is sorted

Best (O(n²))

Selection sort always performs the same number of comparisons regardless of the input array's order.

Average (O(n²))

For random arrays, selection sort requires quadratic time.

Worst (O(n²))

Selection sort always performs the same number of comparisons and swaps regardless of the input array's order.

function selectionSort(arr) {
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    // Find minimum element in unsorted part
    let minIndex = i;

    for (let j = i + 1; j < n; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }

    // Swap found minimum with first element
    if (minIndex !== i) {
      [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
    }
  }

  return arr;
}