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
| Property | Bubble sort | Selection sort |
|---|---|---|
| Technique | Swap neighbors that are out of order | Repeatedly pick the smallest remaining value |
| Best case time | O(n) | O(n²) |
| Average case time | O(n²) | O(n²) |
| Worst case time | O(n²) | O(n²) |
| Extra space | O(1) | O(1) |
| Stable (equal values keep their order) | Yes | No |
| In place (no extra array) | Yes | Yes |
| Needs sorted input | No | No |
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).
| Input | Bubble sort | Selection sort |
|---|---|---|
| Mixed | 40 | 29 |
| Already sorted | 6 | 21 |
| Reversed | 63 | 27 |
| Nearly sorted | 13 | 23 |
| Duplicates | 47 | 31 |
See them run
More comparisons
- Bubble sort vs Insertion sort
- Bubble sort vs Merge sort
- Bubble sort vs Quick sort
- Bubble sort vs Heap sort
- Bubble sort vs Counting sort
- Bubble sort vs Radix sort
- Selection sort vs Insertion sort
- Selection sort vs Merge sort
- Selection sort vs Quick sort
- Selection sort vs Heap sort
- Selection sort vs Counting sort
- Selection sort vs Radix sort
- Insertion sort vs Merge sort
- Insertion sort vs Quick sort
- Insertion sort vs Heap sort
- Insertion sort vs Counting sort
- Insertion sort vs Radix sort
- Merge sort vs Quick sort
- Merge sort vs Heap sort
- Merge sort vs Counting sort
- Merge sort vs Radix sort
- Quick sort vs Heap sort
- Quick sort vs Counting sort
- Quick sort vs Radix sort
- Heap sort vs Counting sort
- Heap sort vs Radix sort
- Counting sort vs Radix sort