Menu
Coddy logo textTech

Bubble Sort

Last updated

Bubble sort repeatedly steps through the list, compares each pair of adjacent elements, and swaps them if they are in the wrong order. After each full pass the largest remaining value has "bubbled" to its correct position at the end, so each pass looks at one fewer element. Press play above to watch the comparisons and swaps, or step through them one at a time.

It is one of the simplest sorting algorithms to understand, which makes it a great first algorithm - but its O(n²) running time makes it impractical for large inputs.

Time & space complexity

CaseComplexityNotes
Best caseO(n)Already sorted, with an early-exit check
Average caseO(n²)Random order
Worst caseO(n²)Reverse-sorted
SpaceO(1)In-place, only a temp variable
StableYesEqual elements keep their relative order

Step by step

StepWhat happens
1Start at the beginning of the array.
2Compare the current element with the next one.
3If they are out of order, swap them.
4Move one position right and repeat to the end (one pass).
5Repeat passes; each pass fixes one more element at the end.
6Stop when a full pass makes no swaps.

Worked example

Sorting [5, 2, 4, 1]:

PassArrayAction
1[2, 4, 1, 5]Swap 5,2, then 5,4, then 5,1; 5 bubbles to the end.
2[2, 1, 4, 5]2,4 in order; swap 4,1; 4,5 in order; 4 is now placed.
3[1, 2, 4, 5]Swap 2,1; the rest are already in order; 2 is placed.
4[1, 2, 4, 5]A full pass makes no swaps, so the array is sorted and the algorithm stops.

When to use bubble sort

Use it whenAvoid it when
Teaching or learning how comparison sorts workSorting large inputs, where O(n²) is far too slow
The input is tiny or nearly sorted (with early exit it approaches O(n))You need the fastest general-purpose sort - use quicksort or merge sort
You need a stable, in-place sort with almost no codeThe data is in random order and performance matters
Detecting whether a short list is already sorted in one passMany writes are costly (e.g. flash memory); selection sort does fewer swaps

Bubble Sort code

A clean, runnable Bubble Sort implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Bubble Sort code in Python

Python
1def bubble_sort(a):2    n = len(a)3    for i in range(n - 1):4        swapped = False5        for j in range(n - 1 - i):6            if a[j] > a[j + 1]:7                a[j], a[j + 1] = a[j + 1], a[j]8                swapped = True9        if not swapped:10            break  # no swaps means the list is already sorted11    return a12
13
14nums = [5, 1, 4, 2, 8]15print("Before:", nums)16bubble_sort(nums)17print("After: ", nums)
Run this code in the Python Playground

Bubble Sort FAQ

What is the time complexity of bubble sort?
Bubble sort runs in O(n²) time in the average and worst cases because of the nested loops. With an early-exit optimization it can reach O(n) on an already-sorted array. It uses O(1) extra space.
Is bubble sort stable?
Yes. Bubble sort only swaps adjacent elements when they are strictly out of order, so equal elements never pass each other and keep their original relative order.
Why is it called bubble sort?
On each pass the largest unsorted value moves step by step toward the end of the array, the way a bubble rises to the surface - hence "bubble" sort.
What is the difference between bubble sort and insertion sort?
Both run in O(n²) and are stable and in-place, but they move data differently: bubble sort repeatedly swaps adjacent out-of-order pairs, while insertion sort takes each element and slides it back into its correct spot in the sorted prefix. Insertion sort usually does fewer writes and runs faster in practice, especially on nearly-sorted data.
When should I use bubble sort instead of quicksort?
Almost never for real workloads - quicksort's O(n log n) average time crushes bubble sort's O(n²) on anything but tiny inputs. Bubble sort is worth reaching for only when the list is very small or nearly sorted, or when you want the simplest possible stable sort for teaching.
Does the early-exit optimization change bubble sort's worst case?
No. Tracking whether a pass made any swaps lets bubble sort stop early and hit O(n) on already-sorted input, but a reverse-sorted array still needs every comparison, so the worst case stays O(n²). The optimization only helps the best and nearly-sorted cases.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED