Selection Sort visualization

Find the minimum of the unsorted part and swap it to the front.

The array is split into a sorted prefix and an unsorted suffix. Each round scans the suffix for its minimum and swaps it into the next prefix slot.

It always performs n(n−1)/2 comparisons, but at most n−1 swaps — handy when writes are expensive.

Complexity

Time: best O(n²), average O(n²), worst O(n²). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure selectionSort(A):
  for i ← 0 to n−2:
    min ← i
    for j ← i+1 to n−1:
      if A[j] < A[min]: min ← j
    swap(A[i], A[min])
  return A

More sorting algorithms