Selection Sort

Sorting

Selection Sort

ā–¾

64

34

25

12

22

11

90

0

1

2

3

4

5

6

Starting Selection Sort. We find the minimum element in each pass and place it at the front.

Presets:

Size:

Timeline Progress:

0%

Step 1 / 47

Comparisons

0

Swaps / Actions

0

Speed:

Shortcuts: Space Play • ←/→ Step • R Reset • M Sound • Z Focus

Implementation Code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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;
}

Complexity Analysis

Best Case

O(n²)

Average Case

O(n²)

Worst Case

O(n²)

Space

O(1)

UnstableIn-Place

Color Legend

Unsorted

Comparing

Swapping

Sorted

Selection Sort divides the array into two parts: a sorted subarray built from left to right and an unsorted subarray. In each iteration, the algorithm finds the minimum element from the unsorted part and moves it to the end of the sorted part. It performs at most O(n) swaps, making it useful when write operations are costly.