Bubble sort is a simple sorting algorithm that compares adjacent elements and swaps them when they are out of order, so each pass carries the largest remaining value to the end. It takes O(n²) time on average and in the worst case, O(n) in the best case when it stops early on a sorted array, and O(1) extra space. This page explains how it works, with step-by-step animations of the first pass, the remaining passes and an already sorted array from the VisiGrab app.
// how bubble sort works
Bubble sort is a simple sorting algorithm that steps through an array, compares each pair of adjacent elements and swaps them when the left one is greater. Each sweep is a pass, and each pass carries the largest unsorted value to the end of the unsorted part. Passes repeat until the array is sorted. Bubble sort takes O(n2) time on average and in the worst case, O(n) in the best case, when it stops early on sorted input, and O(1) extra space.
In ascending order, each pass carries the largest unsorted value right, to the end of the array, like a bubble rising to the surface. Small values move left, at most one place per pass. Bubble sort is also called sinking sort.
Positions count from 0, as in the app. Pass 1 compares positions 0 and 1, then 1 and 2, up to the last pair. Pass k compares n − k pairs. After it, the last k values are final, so n elements need at most n − 1 passes.
In pseudocode:
for i from 0 to n - 2
swapped = false
for j from 0 to n - 2 - i
if a[j] > a[j + 1]
swap a[j] and a[j + 1]
swapped = true
if not swapped
stop
The outer loop counts the finished passes in i. The inner loop runs j from 0 to n - 2 - i and swaps a[j] and a[j + 1] when a[j] > a[j + 1]. A swapped flag, reset on every pass, lets the sort stop early.
The player runs the first pass on the app's default array, 5, 2, 1, 4, 0, 6, 3. 5 moves right until it meets the larger 6, which then moves on to the end: six comparisons and five swaps leave 2, 1, 4, 0, 5, 3, 6.
The larger value of each pair always moves on, so the maximum reaches the end wherever it starts. Nothing else is promised: 0 moved only one place left.
Each new pass starts again at position 0 and compares one pair fewer. Passes 2, 3 and 4 make three, two and one swaps, and the array is sorted after pass 4. The app still runs pass 5, which makes no swaps, and pass 6; an optimized bubble sort would stop after pass 5.
Large values move fast and small ones slowly: they are the rabbits and turtles of bubble sort. 0 starts at position 4 and moves one place left per pass, so it alone forces four passes with swaps. The figure shows the array after every pass.
Without a flag, bubble sort makes all n − 1 passes, even on sorted input. The optimized version, used in the app's code listings, sets swapped to false at the start of each pass and to true on every swap. A pass that ends without a swap has found every adjacent pair in order, so the outer loop breaks. The array 0, 1, 2, 3, 4, 5, 6 is already sorted. Pass 1 compares all six pairs and makes no swaps, so the sort stops.
A further refinement remembers where the last swap happened. Everything after it is sorted, so the next pass can stop there.
O(n), on an already sorted array, but only with the early exit: pass 1 makes n − 1 comparisons, finds no pair to swap and ends the sort. Without it, bubble sort makes all n(n − 1)/2 comparisons even then, O(n2). The third player shows the early exit.
Pass k makes n − k comparisons, so all passes make (n − 1) + (n − 2) + … + 1 = n(n − 1)/2: O(n2). Each swap of out-of-order neighbors removes exactly one inversion, a pair of values in the wrong order, so swaps equal inversions. The default array has 11 inversions, so it takes 11 swaps. An optimized sort makes 20 comparisons on it, and one without the early exit makes all 21.
| Case | Comparisons | Swaps | Time | Extra space |
|---|---|---|---|---|
| Best: already sorted | n − 1 | 0 | O(n) | O(1) |
| Average: random order | Close to n(n − 1)/2 | n(n − 1)/4 on average | O(n2) | O(1) |
| Worst: reverse sorted | n(n − 1)/2 | n(n − 1)/2 | O(n2) | O(1) |
The O(n) best case needs the early exit.
Bubble sort is stable: it swaps only when the left value is strictly greater, so equal values keep their original order. If it also swapped equal neighbors, it would lose stability. Stability matters when records are sorted by a second key. In the app's info dialog, an employee list in name order is sorted by department: a stable sort keeps the names in order within each department.
It is in-place: one temporary value for the swap is enough, so its auxiliary space is O(1). Out-of-place sorts such as merge sort need O(n). The app's info dialog explains both kinds and their memory footprint.
It is adaptive thanks to the early exit: a pass without swaps ends the sort, as the app's info dialog and quiz explain. Without the flag it always makes n(n − 1)/2 comparisons and is not adaptive. Nearly sorted input is fast only if no small value sits far to the right: with the early exit, 6, 0, 1, 2, 3, 4, 5 takes two passes, but 1, 2, 3, 4, 5, 6, 0 takes six.
All three are simple in-place O(n2) sorts. Selection sort swaps the minimum of the unsorted part to the front, at most n − 1 swaps in all. Insertion sort shifts larger values right until the next value fits. It makes one shift per inversion where bubble sort makes one swap, and a shift is one write where a swap is three. So insertion sort is usually the fastest of the three, and library sorts such as Timsort use it for short runs. Bubble sort is usually the slowest on random input, since it makes the most writes.
| Property | Bubble sort | Selection sort | Insertion sort |
|---|---|---|---|
| Best case | O(n), with early exit | O(n2) | O(n) |
| Average and worst case | O(n2) | O(n2) | O(n2) |
| Writes | One swap per inversion | At most n − 1 swaps | One shift per inversion |
| Stable | Yes | No | Yes |
| Adaptive | With early exit | No | Yes |
| Sorted part | Grows from the right, final | Grows from the left, final | Grows from the left, not final |
Merge sort and heap sort take O(n log n) time, and quick sort does on average, so they suit large arrays. Heap sort builds a binary heap.
The app shows the code in all three, linked to the full source on GitHub. They make the same comparisons and swaps, stop at the same point and sort the caller's array in place. Java swaps through a temporary variable, Python with the tuple assignment a[j], a[j + 1] = a[j + 1], a[j] and C++ with std::swap.
Note
In C++ the function takes std::vector<int>&, as the app's listing does: a vector passed by value would be copied, and the caller's vector would stay unsorted. A Java or Python function receives a reference to the caller's array or list and sorts it in place.
The built-in sorts differ in stability. Python's list.sort() and sorted() are stable. Java's Arrays.sort is a dual-pivot quicksort for primitive arrays, where equal values cannot be told apart, and a stable TimSort for objects. C++'s std::sort is not guaranteed to be stable; std::stable_sort is.
The full source code is on GitHub, in Python, Java and C++.
Sorting matters because a sorted array allows binary search in O(log n) time instead of O(n). Production code rarely sorts with bubble sort. It suits:
Bubble sort is not recursive, though a recursive version can be written. It works on a linked list too, since it only touches neighbors. For descending order it swaps when the left value is smaller.
Bubble sort has several variants. Cocktail shaker sort also passes backwards, so turtles move fast. Comb sort compares values a shrinking gap apart. Odd–even sort suits parallel hardware.
// in the app
In VisiGrab bubble sort runs on the default, a random or your own array of seven values, one step per comparison, swap and end of pass: 38 steps on the default array.
Random fills seven distinct values from 0 to 19. Custom opens a seven-cell dialog with values from 0 to 99, and its buttons fill an ascending or a descending array: the best case and the worst case.
Step through every comparison, swap and pass, each with its message, and step back through them. Restart replays the array, and the last array you used comes back next time.
Two tabs. Sorting has five pages: what sorting is and why it speeds up search, in-place and out-of-place sorting, memory footprint, stability and adaptive algorithms. Bubble Sort gives its characteristics and its best, average and worst cases.
The bubbleSort method in Java and the bubble_sort function in Python and C++, each explained with its swapped flag and early exit. Links lead to the full source on GitHub.
Eight questions to check what you have learned before moving on.
Selection sort, insertion sort, merge sort, heap sort and quick sort each have a topic of their own.
// build your own
Download VisiGrab and step through every pass of bubble sort, on the default array, on a sorted one or on an array of your own.
Bubble sort is one of 30+ topics. See them all