1. Home
  2. Design & Analysis of Algorithms
  3. Bubble Sort

Bubble Sort

The simplest sorting algorithm — compare neighbours, swap if they're out of order, repeat. Watch the big values bubble to the end in 3D.

Interactive 3DBeginner8 min readDAAUpdated

Drag to rotate · Right-drag to pan · Click, then scroll to zoom · Space play · Left arrowRight arrow step

What's happening

Bubble sort walks through the array comparing neighbours. Whenever two neighbours are in the wrong order it swaps them, so big values "bubble" to the right.

Pseudocode

  1. procedure bubbleSort(a):
  2. for i ← 0 to n − 2:
  3. swapped ← false
  4. for j ← 0 to n − 2 − i:
  5. if a[j] > a[j + 1]:
  6. swap(a[j], a[j + 1]); swapped ← true
  7. // a[n − 1 − i] is now in its final place
  8. if not swapped: break // already sorted
Read this model as text · 61 steps

One run of the model above, written out step by step. Useful with a screen reader, on a slow connection, or for quick revision. The values may differ from the run on your screen.

  1. Bubble sort walks through the array comparing neighbours. Whenever two neighbours are in the wrong order it swaps them, so big values "bubble" to the right.
  2. Compare a[0] = 12 with a[1] = 5. 12 > 5, so they are in the wrong order.
  3. Swap them: 12 moves right, 5 moves left.
  4. Compare a[1] = 12 with a[2] = 12. 12 ≤ 12 — already in order, no swap.
  5. Compare a[2] = 12 with a[3] = 8. 12 > 8, so they are in the wrong order.
  6. Swap them: 12 moves right, 8 moves left.
  7. Compare a[3] = 12 with a[4] = 3. 12 > 3, so they are in the wrong order.
  8. Swap them: 12 moves right, 3 moves left.
  9. Compare a[4] = 12 with a[5] = 8. 12 > 8, so they are in the wrong order.
  10. Swap them: 12 moves right, 8 moves left.
  11. Compare a[5] = 12 with a[6] = 5. 12 > 5, so they are in the wrong order.
  12. Swap them: 12 moves right, 5 moves left.
  13. Compare a[6] = 12 with a[7] = 15. 12 ≤ 15 — already in order, no swap.
  14. Compare a[7] = 15 with a[8] = 8. 15 > 8, so they are in the wrong order.
  15. Swap them: 15 moves right, 8 moves left.
  16. Compare a[8] = 15 with a[9] = 8. 15 > 8, so they are in the wrong order.
  17. Swap them: 15 moves right, 8 moves left.
  18. End of pass 1: the biggest unsorted value 15 has reached its final position (index 9).
  19. Compare a[0] = 5 with a[1] = 12. 5 ≤ 12 — already in order, no swap.
  20. Compare a[1] = 12 with a[2] = 8. 12 > 8, so they are in the wrong order.
  21. Swap them: 12 moves right, 8 moves left.
  22. Compare a[2] = 12 with a[3] = 3. 12 > 3, so they are in the wrong order.
  23. Swap them: 12 moves right, 3 moves left.
  24. Compare a[3] = 12 with a[4] = 8. 12 > 8, so they are in the wrong order.
  25. Swap them: 12 moves right, 8 moves left.
  26. Compare a[4] = 12 with a[5] = 5. 12 > 5, so they are in the wrong order.
  27. Swap them: 12 moves right, 5 moves left.
  28. Compare a[5] = 12 with a[6] = 12. 12 ≤ 12 — already in order, no swap.
  29. Compare a[6] = 12 with a[7] = 8. 12 > 8, so they are in the wrong order.
  30. Swap them: 12 moves right, 8 moves left.
  31. Compare a[7] = 12 with a[8] = 8. 12 > 8, so they are in the wrong order.
  32. Swap them: 12 moves right, 8 moves left.
  33. End of pass 2: the biggest unsorted value 12 has reached its final position (index 8).
  34. Compare a[0] = 5 with a[1] = 8. 5 ≤ 8 — already in order, no swap.
  35. Compare a[1] = 8 with a[2] = 3. 8 > 3, so they are in the wrong order.
  36. Swap them: 8 moves right, 3 moves left.
  37. Compare a[2] = 8 with a[3] = 8. 8 ≤ 8 — already in order, no swap.
  38. Compare a[3] = 8 with a[4] = 5. 8 > 5, so they are in the wrong order.
  39. Swap them: 8 moves right, 5 moves left.
  40. Compare a[4] = 8 with a[5] = 12. 8 ≤ 12 — already in order, no swap.
  41. Compare a[5] = 12 with a[6] = 8. 12 > 8, so they are in the wrong order.
  42. Swap them: 12 moves right, 8 moves left.
  43. Compare a[6] = 12 with a[7] = 8. 12 > 8, so they are in the wrong order.
  44. Swap them: 12 moves right, 8 moves left.
  45. End of pass 3: the biggest unsorted value 12 has reached its final position (index 7).
  46. Compare a[0] = 5 with a[1] = 3. 5 > 3, so they are in the wrong order.
  47. Swap them: 5 moves right, 3 moves left.
  48. Compare a[1] = 5 with a[2] = 8. 5 ≤ 8 — already in order, no swap.
  49. Compare a[2] = 8 with a[3] = 5. 8 > 5, so they are in the wrong order.
  50. Swap them: 8 moves right, 5 moves left.
  51. Compare a[3] = 8 with a[4] = 8. 8 ≤ 8 — already in order, no swap.
  52. Compare a[4] = 8 with a[5] = 8. 8 ≤ 8 — already in order, no swap.
  53. Compare a[5] = 8 with a[6] = 8. 8 ≤ 8 — already in order, no swap.
  54. End of pass 4: the biggest unsorted value 8 has reached its final position (index 6).
  55. Compare a[0] = 3 with a[1] = 5. 3 ≤ 5 — already in order, no swap.
  56. Compare a[1] = 5 with a[2] = 5. 5 ≤ 5 — already in order, no swap.
  57. Compare a[2] = 5 with a[3] = 8. 5 ≤ 8 — already in order, no swap.
  58. Compare a[3] = 8 with a[4] = 8. 8 ≤ 8 — already in order, no swap.
  59. Compare a[4] = 8 with a[5] = 8. 8 ≤ 8 — already in order, no swap.
  60. End of pass 5: the biggest unsorted value 8 has reached its final position (index 5).
  61. No swaps in this whole pass — the array is already sorted, so we stop early. That's why bubble sort's best case is O(n).

Try this in the 3D model

  • Press ▶ and watch the tallest bar. Where does it end up after the first pass?
  • Load Already sorted and play it. How many passes does it need? That's the best case.
  • Load Reversed. Count the swaps — every single comparison causes one. That's the worst case.
  • Type your own numbers, like 5, 1, 4, 2, 8, and sort them.

The idea

Bubble sort repeatedly walks through the array and compares neighbouring elements. If a pair is in the wrong order, it swaps them.

After one full pass, the largest value has been pushed all the way to the end — like a bubble rising to the top of water. After the second pass, the second-largest is in place, and so on.

Analogy: lining up students by height by only letting neighbours swap places. The tallest student keeps swapping forward until they reach the end of the line.

Step by step

For an array of n elements:

  1. Pass 1: compare positions (0,1), (1,2), …, (n−2, n−1). Swap any pair where the left is bigger. Now the biggest element is at index n−1.
  2. Pass 2: do the same but stop one earlier — the last element is already final.
  3. Keep going. After n−1 passes, everything is sorted.

Optimisation: keep a flag swapped. If a whole pass makes no swaps, the array is already sorted — stop early. This makes the best case (already sorted input) only O(n).

In the model, green bars are in their final position; the yellow pair is being compared; red means a swap. Swapped bars arc around each other in 3D so you can follow them.

Code

def bubble_sort(a):
    n = len(a)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):          # the last i items are already in place
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swapped = True
        if not swapped:                      # no swaps → already sorted
            break
    return a

print(bubble_sort([5, 1, 4, 2, 8]))   # [1, 2, 4, 5, 8]
#include <iostream>
#include <vector>
#include <utility>
using namespace std;

void bubbleSort(vector<int>& a) {
    int n = a.size();
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (a[j] > a[j + 1]) {
                swap(a[j], a[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break;
    }
}

int main() {
    vector<int> a = {5, 1, 4, 2, 8};
    bubbleSort(a);
    for (int x : a) cout << x << " ";   // 1 2 4 5 8
}

How slow is it?

Pass 1 makes n−1 comparisons, pass 2 makes n−2, … down to 1:

(n−1) + (n−2) + … + 1 = n(n−1)/2

For 10 elements that’s 45 comparisons; for 10,000 elements, almost 50 million. Because the work grows with n², bubble sort is called a quadratic, O(n²) algorithm. Compare that with merge sort, which needs only about 130,000 comparisons for 10,000 elements.

Properties

Property Bubble sort
In-place (no extra array) ✅ Yes — O(1) extra space
Stable (equal items keep their order) ✅ Yes
Adaptive (fast on nearly-sorted data) ✅ With the swapped flag
Good for large data ❌ No

When would you actually use it?

Honestly, almost never in real software — but it is the perfect first sorting algorithm because it teaches comparisons, swaps, passes, loop invariants and Big-O analysis. It’s also handy for tiny or nearly-sorted arrays.

Common mistakes

  • Running the inner loop to n−1 every time instead of n−1−i (still correct, just wasted work).
  • Accessing a[j+1] when j = n−1 — an out-of-bounds bug.
  • Forgetting to reset swapped = False at the start of each pass.

Complexity at a glance

Case / operationTimeWhy
Best case (already sorted)O(n)One pass with no swaps, then stop early.
Average caseO(n²)About n²/4 swaps.
Worst case (reversed)O(n²)n(n−1)/2 comparisons and swaps.
Extra spaceO(1)

Quick check

Test yourself — pick an answer to see if you got it.

1. After the first pass of bubble sort, which element is guaranteed to be in its final position?

2. How many comparisons does bubble sort make in the worst case for n = 6?

3. What does the 'swapped' flag let bubble sort do?

4. Is bubble sort stable (equal values keep their original order)?

Saved in this browser.
Spotted a mistake or a bug in the 3D model?

Report a mistake

in Bubble Sort. Thank you — every report makes the lesson better for the next reader.

We'll also include a link to the step of the 3D model you're on and your browser type, so we can reproduce it.