Selection Sort

Finds the minimum from the unsorted part and places it at the front.

Best: O(n²) · Avg: O(n²) · Worst: O(n²) · Space: O(1)

16
43
70
30
62
26
52
89
90
54
78
78
26
27
22
Speed5
Size15
TypeScript
function selectionSort(arr: number[]): number[] {
  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]];
    }
  }
  return arr;
}