DSA Tracker

Visualize

Selection Sort

time O(n^2)space O(1)

The array splits into a sorted prefix (empty at first) and an unsorted suffix. Each pass finds the SMALLEST value anywhere in the unsorted suffix and swaps it into the very next open slot — so the sorted prefix only ever grows by one confirmed-correct element per pass, and after n-1 passes there's nowhere left for anything to be out of place.

Details

Animated on: Sort nums = [64, 25, 12, 22, 11] in ascending order using selection sort.

Problem:Selection SortEasy

Sorting

step 1 / 9

64
[0]
25
[1]
12
[2]
22
[3]
11
[4]

Pass i=0: scan the whole array for its minimum. Start with minIdx=0 (64) as the candidate.

  • i=0· arr[0] = 64
Pseudocode
1FUNCTION selectionSort(arr):
2 n = the length of arr
3 FOR i from 0 to n-2:
4 minIdx = i (assume the smallest sits here)
5 FOR j from i+1 to n-1:
6 IF arr[j] < arr[minIdx]:
7 minIdx = j
8 swap arr[i] and arr[minIdx]

← / → step · space play · Home restart

Every step in words

Show all 9 steps
  1. Pass i=0: scan the whole array for its minimum. Start with minIdx=0 (64) as the candidate.
  2. Scanning j=1..4: 25<64→minIdx=1; 12<25→minIdx=2; 22<12? no; 11<12→minIdx=4. Smallest found: 11 at index 4.
  3. Swap arr[0] and arr[4]: [11, 25, 12, 22, 64]. Index 0 is now correctly placed.
  4. Pass i=1: scan indices 1..4. 12<25→minIdx=2; 22<12? no; 64<12? no. Smallest of the suffix: 12 at index 2.
  5. Swap arr[1] and arr[2]: [11, 12, 25, 22, 64]. Index 1 is now correctly placed.
  6. Pass i=2: scan indices 2..4. 22<25→minIdx=3; 64<22? no. Smallest of the suffix: 22 at index 3.
  7. Swap arr[2] and arr[3]: [11, 12, 22, 25, 64]. Index 2 is now correctly placed.
  8. Pass i=3: scan index 4 only. 64<25? no. minIdx stays 3 — arr[3] was already the smallest remaining. Swap with itself (no change).
  9. All 4 passes done (n-1 = 4 for n=5). Sorted: [11, 12, 22, 25, 64].

Now solve it yourself

Watching is the first half. The second is writing it without the animation.