Algorithm · Sorting and selection · O(n²) worst, O(n) sorted
Bubble sort
Swap adjacent out-of-order pairs, pass after pass, until a pass makes no swap. Stable and in place, O(n²) in general, O(n) on sorted input.
The full derivation, edge cases and exercises are in the lesson Bubble, selection and insertion sort. Open it full width in the playground.
On this page
The idea
Each pass carries the largest remaining element to the end of the unsorted part, like a bubble rising. With the early exit, a pass without swaps proves the array is sorted. It is a teaching sort: its swap count equals the number of inversions, which makes it slow on almost any real input.
Steps
- Compare a[i] and a[i + 1] for every i in the unsorted part, swapping when a[i + 1] < a[i].
- After the pass, the last unsorted slot holds its final value.
- Repeat until a pass makes no swap.
Invariants
What holds at every step; the correctness argument rests on these.
- After k passes, the last k elements are the k largest, in their final order.
- Only strictly smaller neighbours are swapped, so equal elements keep their order (stable).
Complexity
| Case | Time | Extra space | Notes |
|---|---|---|---|
| Best case (sorted) | O(n) | O(1) | One pass, no swaps. |
| Average / worst | O(n²) | O(1) |
When to use it
Use it when
- Teaching invariants and inversions, or verifying that a tiny array is already sorted.
Avoid it when
- Any real sorting job: insertion sort does the same work with fewer writes, and the built-in sort is O(n log n).
Step through it
The interactive lab for bubble sort: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.
Implementation in four languages
Bubble sort in four languages, checked against the merge sort fixture (which also verifies stability) and random inputs compared with the language's stable built-in sort.
namespace Bekadan.Dsa.Examples.Sorting;
/// <summary>
/// Bubble sort (with the early exit) and insertion sort. Both are stable and in
/// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
/// </summary>
public static class ElementarySorts
{
public static void BubbleSort<T>(T[] items, Comparison<T> compare)
{
for (int end = items.Length - 1; end > 0; end--)
{
bool swapped = false;
for (int i = 0; i < end; i++)
{
if (compare(items[i + 1], items[i]) < 0) // strictly smaller: equal items never swap (stable)
{
(items[i], items[i + 1]) = (items[i + 1], items[i]);
swapped = true;
}
}
if (!swapped)
break; // no swap in a whole pass: already sorted
}
}
public static void InsertionSort<T>(T[] items, Comparison<T> compare)
{
for (int i = 1; i < items.Length; i++)
{
T key = items[i];
int j = i - 1;
while (j >= 0 && compare(items[j], key) > 0) // strictly greater: equal items stay in order (stable)
{
items[j + 1] = items[j];
j--;
}
items[j + 1] = key;
}
}
}
Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/ElementarySorts.cs
"""Bubble sort (with the early exit) and insertion sort.
Both are stable and in place: Θ(n²) comparisons in the worst case, Θ(n) on
already sorted input.
"""
from collections.abc import Callable
from typing import Any
def _identity(item: Any) -> Any:
return item
def bubble_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
for end in range(len(items) - 1, 0, -1):
swapped = False
for i in range(end):
if key(items[i + 1]) < key(items[i]): # strictly smaller: equal items never swap (stable)
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
if not swapped:
break # no swap in a whole pass: already sorted
def insertion_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and key(items[j]) > key(current): # strictly greater: equal items stay in order (stable)
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
Tested on CPython 3.14.0 · examples/python/dsa_examples/elementary_sorts.py
package dev.bekadan.dsa.sorting;
import java.util.Comparator;
/**
* Bubble sort (with the early exit) and insertion sort. Both are stable and in
* place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
*/
public final class ElementarySorts {
private ElementarySorts() {
}
public static <T> void bubbleSort(T[] items, Comparator<? super T> comparator) {
for (int end = items.length - 1; end > 0; end--) {
boolean swapped = false;
for (int i = 0; i < end; i++) {
if (comparator.compare(items[i + 1], items[i]) < 0) { // strictly smaller: equal items never swap (stable)
T tmp = items[i];
items[i] = items[i + 1];
items[i + 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break; // no swap in a whole pass: already sorted
}
}
}
public static <T> void insertionSort(T[] items, Comparator<? super T> comparator) {
for (int i = 1; i < items.length; i++) {
T key = items[i];
int j = i - 1;
while (j >= 0 && comparator.compare(items[j], key) > 0) { // strictly greater: equal items stay in order
items[j + 1] = items[j];
j--;
}
items[j + 1] = key;
}
}
}
Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/ElementarySorts.java
#pragma once
#include <cstddef>
#include <functional>
#include <span>
#include <utility>
namespace bekadan::dsa {
// Bubble sort (with the early exit) and insertion sort. Both are stable and in
// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
template <typename T, typename Less = std::less<>>
void bubble_sort(std::span<T> items, Less less = {}) {
for (std::size_t end = items.size(); end > 1; --end) {
bool swapped = false;
for (std::size_t i = 0; i + 1 < end; ++i) {
if (less(items[i + 1], items[i])) { // strictly smaller: equal items never swap (stable)
std::swap(items[i], items[i + 1]);
swapped = true;
}
}
if (!swapped)
break; // no swap in a whole pass: already sorted
}
}
template <typename T, typename Less = std::less<>>
void insertion_sort(std::span<T> items, Less less = {}) {
for (std::size_t i = 1; i < items.size(); ++i) {
T key = std::move(items[i]);
std::size_t j = i; // the gap is at j; compare with items[j - 1]
while (j > 0 && less(key, items[j - 1])) { // strictly greater on the left: equal items stay in order
items[j] = std::move(items[j - 1]);
--j;
}
items[j] = std::move(key);
}
}
} // namespace bekadan::dsa
Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/elementary_sorts.hpp
Learn more
Lessons
- Bubble, selection and insertion sort· M13 Sorting
Data structures it uses
Comparisons
- Bubble sort vs insertion sort· Two quadratic, stable, in-place sorts on one array, with merge sort as an optional third lane. Counts are compared, not timed.
Problems, patterns and exercises
- Complexity exerciseInner loop that depends on the outer index· Θ(n²)