Visualize

Pattern visualizer

Selection Sort

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. Animated on: Sort nums = [64, 25, 12, 22, 11] in ascending order using selection sort..

Sorting

time O(n^2)space O(1)step 1 / 9
64
[0]
25
[1]
12
[2]
22
[3]
11
[4]
line 4

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

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

Where to practice Sorting