Skip to content
SimpleScope

Sorting

Bubble sort vs Selection sort

Bubble sort and Selection sort both put an array in order, in different ways. Bubble sort: swap neighbors that are out of order. Selection sort: repeatedly pick the smallest remaining value. In the worst case both take O(n²), so the choice comes down to the other differences below.

At a glance

PropertyBubble sortSelection sort
TechniqueSwap neighbors that are out of orderRepeatedly pick the smallest remaining value
Best case timeO(n)O(n²)
Average case timeO(n²)O(n²)
Worst case timeO(n²)O(n²)
Extra spaceO(1)O(1)
Stable (equal values keep their order)YesNo
In place (no extra array)YesYes
Needs sorted inputNoNo

When to choose each

Choose bubble sort when

you want the simplest sort to explain, on tiny or almost sorted data.

Avoid it when

the data is large.

Choose selection sort when

writing to memory is expensive, since it makes at most n - 1 swaps.

Avoid it when

the data is large, or you hope sorted input will be fast.

The same inputs, counted

These numbers come from running both real implementations: operations (comparisons plus writes, a swap counting as two writes).

InputBubble sortSelection sort
Mixed4029
Already sorted621
Reversed6327
Nearly sorted1323
Duplicates4731

See them run

More comparisons