Bubble Sort, step by step.

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

What is bubble sort?

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.

Why is it called bubble sort?

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.

Bubble sort algorithm: passes and loops

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.

Bubble sort example: the first pass

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 first pass

All steps as text
  1. Sort the array using the Bubble Sort algorithm.
  2. Starting from the beginning of the array, compare each pair of adjacent elements.
  3. Swap the elements, since the first element of the pair is greater than the second.
  4. Move to the next pair and compare elements at positions 1 and 2.
  5. Swap the elements, since the first element of the pair is greater than the second.
  6. Move to the next pair and compare elements at positions 2 and 3.
  7. Swap the elements, since the first element of the pair is greater than the second.
  8. Move to the next pair and compare elements at positions 3 and 4.
  9. Swap the elements, since the first element of the pair is greater than the second.
  10. Move to the next pair and compare elements at positions 4 and 5.
  11. Move to the next pair and compare elements at positions 5 and 6.
  12. Swap the elements, since the first element of the pair is greater than the second.
  13. After each pass, the largest element from the unsorted part settles at its correct position.
  14. Pass 1 made six comparisons and five swaps. 6, the largest element, is now at the end.
Bubble Sort — The first pass. Last step: Pass 1 made six comparisons and five swaps. 6, the largest element, is now at the end.

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.

Bubble sort example: the remaining passes

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.

The remaining passes

All steps as text
  1. The first pass has moved 6, the largest element, to its correct position. Each new pass compares one pair fewer.
  2. Return to the beginning of the array to repeat the process until the entire array is sorted. Compare the elements at positions 0 and 1.
  3. Swap the elements, since the first element of the pair is greater than the second.
  4. Move to the next pair and compare elements at positions 1 and 2.
  5. Move to the next pair and compare elements at positions 2 and 3.
  6. Swap the elements, since the first element of the pair is greater than the second.
  7. Move to the next pair and compare elements at positions 3 and 4.
  8. Move to the next pair and compare elements at positions 4 and 5.
  9. Swap the elements, since the first element of the pair is greater than the second.
  10. After each pass, the largest element from the unsorted part settles at its correct position.
  11. Return to the beginning of the array. Compare the elements at positions 0 and 1.
  12. Move to the next pair and compare elements at positions 1 and 2.
  13. Swap the elements, since the first element of the pair is greater than the second.
  14. Move to the next pair and compare elements at positions 2 and 3.
  15. Move to the next pair and compare elements at positions 3 and 4.
  16. Swap the elements, since the first element of the pair is greater than the second.
  17. After each pass, the largest element from the unsorted part settles at its correct position.
  18. Return to the beginning of the array. Compare the elements at positions 0 and 1.
  19. Swap the elements, since the first element of the pair is greater than the second.
  20. Move to the next pair and compare elements at positions 1 and 2.
  21. Move to the next pair and compare elements at positions 2 and 3.
  22. After each pass, the largest element from the unsorted part settles at its correct position.
  23. Return to the beginning of the array. Compare the elements at positions 0 and 1.
  24. Move to the next pair and compare elements at positions 1 and 2.
  25. After each pass, the largest element from the unsorted part settles at its correct position.
  26. Return to the beginning of the array. Compare the elements at positions 0 and 1.
  27. With all elements now in their correct positions, the array is sorted.
  28. The pass before the last one made no swaps, so an optimized bubble sort would have stopped after it.
Bubble Sort — The remaining passes. Last step: The array is sorted: 0, 1, 2, 3, 4, 5, 6.

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.

Seven rows of seven cells, labeled Start and Pass 1 to Pass 6. Start is the unsorted array 5, 2, 1, 4, 0, 6, 3; after pass 1 it is 2, 1, 4, 0, 5, 3, 6; after pass 2, 1, 2, 0, 4, 3, 5, 6; after pass 3, 1, 0, 2, 3, 4, 5, 6; after passes 4 to 6, 0, 1, 2, 3, 4, 5, 6. Under each pass row a bracket covers the settled cells at the right end, labeled Sorted in the first: one cell after pass 1, two after pass 2, and so on, and all seven after pass 6.
Each pass settles the largest unsorted value at the right end and widens the Sorted bracket, while 0 moves left only one place per pass until it reaches position 0.

Optimized bubble sort: stopping early

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.

An already sorted array

All steps as text
  1. Sort the array using the Bubble Sort algorithm.
  2. Starting from the beginning of the array, compare each pair of adjacent elements.
  3. Move to the next pair and compare elements at positions 1 and 2.
  4. Move to the next pair and compare elements at positions 2 and 3.
  5. Move to the next pair and compare elements at positions 3 and 4.
  6. Move to the next pair and compare elements at positions 4 and 5.
  7. Move to the next pair and compare elements at positions 5 and 6.
  8. If no swaps occur after comparing all adjacent pairs, stop — the array is already sorted.
  9. One pass, six comparisons, no swaps: on an already sorted array, bubble sort finishes in O(n).
Bubble Sort — An already sorted array. Last step: The array 0, 1, 2, 3, 4, 5, 6 is unchanged: one pass with no swaps finished the sort.

A further refinement remembers where the last swap happened. Everything after it is sorted, so the next pass can stop there.

What is the best-case time complexity of bubble sort?

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.

Bubble sort time complexity: best, average and worst case

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.

CaseComparisonsSwapsTimeExtra space
Best: already sortedn − 10O(n)O(1)
Average: random orderClose to n(n − 1)/2n(n − 1)/4 on averageO(n2)O(1)
Worst: reverse sortedn(n − 1)/2n(n − 1)/2O(n2)O(1)

The O(n) best case needs the early exit.

Is bubble sort stable, in-place and adaptive?

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.

Bubble sort vs selection sort vs insertion sort

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.

PropertyBubble sortSelection sortInsertion sort
Best caseO(n), with early exitO(n2)O(n)
Average and worst caseO(n2)O(n2)O(n2)
WritesOne swap per inversionAt most n − 1 swapsOne shift per inversion
StableYesNoYes
AdaptiveWith early exitNoYes
Sorted partGrows from the right, finalGrows from the left, finalGrows 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.

Bubble sort in Python, Java and C++

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++.

When bubble sort is used

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:

  • Teaching: each step is one comparison and at most one swap.
  • Very small arrays, and nearly sorted ones with values a place or two out of position.
  • A single pass that checks whether an array is sorted.
  • Polygon filling in graphics, where edge order changes only between neighbors from one scan line to the next.

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.

Three animations here.
The whole topic 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.

Your own 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.

Forward and back

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.

Theory and complexity

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.

Python, Java and C++

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.

Quiz

Eight questions to check what you have learned before moving on.

Five more sorts

Selection sort, insertion sort, merge sort, heap sort and quick sort each have a topic of their own.

Sort an array
swap by swap.

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