Interactive demo

Selection Sort Visualization

Selection sort searches the smallest of the remaining elements and swaps it to the front, one position after the other. It needs few writes, but always O(n²) comparisons.

Your browser does not support the HTML5 canvas tag.

Whatever the starting order: selection sort always needs the same 55 comparisons for 11 elements. With “Few unique values” it shows that it is not stable.

Playback

Comparisons
0
Writes
0

Array

Legend

  • Unsorted element
  • Smallest so far
  • Compared element
  • Final position

Runtime and properties

Best case

O(n²)

Even a sorted array is searched completely for each next minimum.

Average case

O(n²)

Always n(n − 1)/2 comparisons, independent of the input.

Worst case

O(n²)

The same n(n − 1)/2 comparisons, but never more than n − 1 swaps.

Extra memory

O(1)

Only the position of the current minimum is kept.

Stable

No

Swapping the minimum to the front can jump over an equal element.

In-place

Yes

Elements are only swapped within the array.

n is the number of elements. O(n log n) is the best a sorting algorithm based on comparisons can achieve.

Compared with the other sorting algorithms

AlgorithmBest caseAverage caseWorst caseExtra memoryStableIn-place
Bubble sortO(n)O(n²)O(n²)O(1)YesYes
Selection sort this pageO(n²)O(n²)O(n²)O(1)NoYes
Insertion sortO(n)O(n²)O(n²)O(1)YesYes
Shell sortO(n log n)≈ O(n1.25)O(n1.5)O(1)NoYes
Tree sortO(n log n)O(n log n)O(n²)O(n)YesNo
Tournament sortO(n log n)O(n log n)O(n log n)O(n)YesNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)NoYes
SmoothsortO(n)O(n log n)O(n log n)O(1)NoYes
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNo
Patience sortO(n)O(n log n)O(n log n)O(n)YesNo
TimsortO(n)O(n log n)O(n log n)O(n)YesNo
Block sortO(n)O(n log n)O(n log n)O(1)YesYes
QuicksortO(n log n)O(n log n)O(n²)O(log n)NoYes
IntrosortO(n log n)O(n log n)O(n log n)O(log n)NoYes
FluxsortO(n)O(n log n)O(n log n)O(n)YesNo
CrumsortO(n)O(n log n)O(n log n)O(log n)NoYes

1. Search the minimum

Starting at the front of the unsorted part, every remaining element is compared with the smallest one found so far.

2. Swap it to the front

The smallest element is swapped to the front of the unsorted part. There it is at its final position, and the unsorted part shrinks by one.

3. Few writes, many comparisons

Selection sort never needs more than n − 1 swaps, which helps when writing is expensive. But it cannot stop early: even a sorted array costs n(n − 1)/2 comparisons.