Sorting Algorithms

How Selection Sort Works

Selection sort scans for the smallest remaining value and swaps it into place, using exactly n-1 swaps whatever the input. See why that makes it predictable but not fast.

  • Waiting
  • Being compared
  • Just moved
  • In final position
1/97

Selection sort, 12 values in random order.

Counters

Comparisons
0
Writes
0
n
12
Average case
O(n²)

Settings

More options
Starting order

Two to 48 numbers. Sorted in exactly the order you type them.

Selection sort

  1. 1for i in 0..n-2:
  2. 2 min = i
  3. 3 for j in i+1..n-1:
  4. 4 if a[j] < a[min]:
  5. 5 min = j
  6. 6 swap(i, min)
  7. 7 // a[i] is now final

The same array, every algorithm

Comparisons on the values above, cheapest first. Writes in the second line. Run it on nearly sorted values to see the O(n log n) sorts lose.

  1. Merge3344 writes
  2. Quick3340 writes
  3. Insertion4042 writes
  4. Shell4637 writes
  5. Heap5166 writes
  6. Bubble6062 writes
  7. Selection6618 writes

How the seven compare

AlgorithmBestAverageWorstExtra memoryStable
BubbleO(n)O(n²)O(n²)O(1)Yes
InsertionO(n)O(n²)O(n²)O(1)Yes
SelectionO(n²)O(n²)O(n²)O(1)No
ShellO(n log n)O(n√n)O(n²)O(1)No
MergeO(n log n)O(n log n)O(n log n)O(n)Yes
QuickO(n log n)O(n log n)O(n²)O(log n)No
HeapO(n log n)O(n log n)O(n log n)O(1)No

Scroll the table sideways for the rest of the columns.

Stable means equal values keep their original order.

Complexity

BestAverageWorstExtra memory
O(n²)O(n²)O(n²)O(1)

How selection sort works

Selection sort finds the minimum of the unsorted region, swaps it into the region's first position, and shrinks the region by one. It always performs about n²/2 comparisons whatever the input, and exactly n-1 swaps. That swap count is the fewest of any comparison sort that works in place.

When to use it

  • Use it when writes are expensive and reads are cheap: flash memory, or records so large that moving one costs far more than comparing two. n-1 swaps is hard to beat.
  • Use it when predictable timing matters more than speed: it takes the same time on every input of a given size.
  • Avoid it as a general sort. It cannot exploit existing order at all, so even a sorted array costs the full n².

More sorting algorithms