Bubble Sort Explained: Beginner-Friendly Guide in 6 Easy Steps

I still remember the first time someone told me to sort a list of numbers without using the built-in sort. I sat there staring at my screen for a solid ten minutes, getting nowhere. Then I came across bubble sort, and something just clicked. Sorting stopped feeling like magic.

If you’re learning to code, cramming for a CS exam, or getting ready for a technical interview, bubble sort is probably the first sorting algorithm you’ll meet. It isn’t fast. Honestly, it’s pretty slow. But it’s the easiest one to wrap your head around, and once you get it, every other sorting algorithm makes a lot more sense.

So let’s go through it step by step, the way I wish someone had done it for me.

What Is Bubble Sort?

Bubble sort goes through a list over and over, looking at two neighbouring items at a time. If they’re in the wrong order, it swaps them. It keeps going until the whole list is sorted.

Why “bubble”? On every pass, the biggest number that’s still unsorted floats up to the end of the list, kind of like a bubble rising to the top of a fizzy drink.

That’s basically it. Compare, swap, repeat.

How Does Bubble Sort Work? A Step-by-Step Example

We’ll sort this small list from smallest to largest:

[5, 3, 8, 4, 2]

Pass 1

  • Compare 5 and 3. 5 is bigger, so they swap: [3, 5, 8, 4, 2]
  • Compare 5 and 8. Already fine, so nothing happens.
  • Compare 8 and 4. Swap: [3, 5, 4, 8, 2]
  • Compare 8 and 2. Swap: [3, 5, 4, 2, 8]

8 has floated all the way to the end, and that’s where it stays.

Pass 2

  • Compare 3 and 5. Fine, no swap.
  • Compare 5 and 4. Swap: [3, 4, 5, 2, 8]
  • Compare 5 and 2. Swap: [3, 4, 2, 5, 8]

5 is now in its final spot too.

Pass 3

  • Compare 3 and 4. Fine, no swap.
  • Compare 4 and 2. Swap: [3, 2, 4, 5, 8]

Pass 4

  • Compare 3 and 2. Swap: [2, 3, 4, 5, 8]

And we’re done: [2, 3, 4, 5, 8].

Here’s something worth noticing. Each pass locks one more number into place at the end, so the next pass doesn’t need to look at it again. Keep that in mind, because it’s exactly how we’ll speed up the code later.

Try Bubble Sort Yourself

Watch the algorithm compare neighbouring values and move the largest unsorted value to the right on each pass. Use the controls to step through it or let it run.

Ready. Press “Next step” to compare the first pair.
Comparisons: 0Swaps: 0Pass: 1

Bubble Sort Algorithm in Plain English

Before we get to any code, here’s the logic in everyday words:

  1. Start at the beginning of the list.
  2. Look at the first two items. If the first one is bigger, swap them.
  3. Move one spot along and do the same for the next pair.
  4. When you reach the end, the largest item is in its correct place.
  5. Go back to the start and repeat, skipping the items that are already sorted.
  6. Stop when you get through a whole pass without a single swap.

Bubble Sort in Python

The following is a simple version that’s easy to follow:

python

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

numbers = [5, 3, 8, 4, 2]
print(bubble_sort(numbers))  # [2, 3, 4, 5, 8]

The outer loop counts the passes, and the inner loop does the comparing and swapping. The part that trips people up is n - i - 1. It makes the inner loop a little shorter on every pass, because the last i items are already in place and there’s no point checking them again.

The Optimized Bubble Sort

The basic version has a problem. Give it a list that’s already sorted, or one that gets sorted halfway through, and it still grinds through every remaining pass for nothing.

The fix is a small flag. If a pass finishes with zero swaps, the list is sorted and we can quit early.

python

def optimized_bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        swapped = False
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

It’s a tiny change, but it helps a lot on lists that are nearly sorted. Interviewers also love asking about it as a follow-up, so it’s worth remembering.

Bubble Sort Time Complexity

This is the section that explains why nobody uses bubble sort for real work.

CaseTime ComplexityWhat it means
Best caseO(n)List is already sorted (optimized version only)
Average caseO(n²)Random order
Worst caseO(n²)List is in reverse order

Space complexity: O(1). It sorts the list in place, so the only extra memory it needs is one temporary variable for swapping.

So what does O(n²) actually feel like? With 1,000 items, the basic version can make up to 499,500 comparisons. Go up to 100,000 items and the number gets huge. The work grows with the square of the input size, and that gets painful quickly.

Is Bubble Sort Stable?

Yes. Bubble sort is a stable sorting algorithm, which means two equal items stay in the same order they started in. It only swaps when one item is strictly bigger than the other, so equal values never trade places. This matters if you’re sorting records by one field and want to keep an earlier ordering intact.

Advantages of Bubble Sort

  • Dead simple. You can explain it to a friend in about a minute.
  • Easy to write. A few lines, no recursion, no special data structures.
  • In-place. It barely uses any extra memory.
  • Stable. Equal items keep their order.
  • Spots sorted lists. With the flag added, it finishes fast when there’s nothing left to do.

Disadvantages of Bubble Sort

  • Slow on big lists. O(n²) is the dealbreaker.
  • Too many swaps. Items only move one position at a time, which wastes effort.
  • Outperformed by nearly everything. Even insertion sort, which is just as simple, usually does better.

Bubble Sort vs. Other Sorting Algorithms

AlgorithmAverage TimeStableBest for
Bubble sortO(n²)YesLearning, tiny lists
Insertion sortO(n²)YesSmall or nearly sorted data
Selection sortO(n²)NoTeaching, minimal swaps
Merge sortO(n log n)YesLarge datasets, stability needed
Quick sortO(n log n)NoGeneral-purpose sorting

If you’re sorting real data in a real project, just use your language’s built-in sort. Python’s sorted() and list.sort() run on Timsort, which will beat anything you write by hand.

When Should You Actually Use Bubble Sort?

Honestly, almost never in production. It still has its uses though:

  • Learning. It teaches you loops, comparisons, swapping and how to think about efficiency.
  • Interviews. You might be asked to write it, or to explain why it’s slow.
  • Very small or already sorted lists. The optimized version can tell a list is sorted after a single pass. For nearly sorted data, though, insertion sort is usually the better pick.
  • Visualizations. Watching bubble sort animate is strangely satisfying, and it’s a great way to build intuition.

Common Mistakes Beginners Make

  1. Not shrinking the inner loop. It still works, but you waste time re-checking items that are already sorted.
  2. Off-by-one errors. Looping up to n instead of n - i - 1 can throw an index out of range error.
  3. Comparing the wrong way round. Use > for ascending order and < for descending.
  4. Leaving out the swapped flag. Without it, you lose the early exit.
  5. Swapping equal values. Use >, not >=, for ascending order. Swapping equal items can change their original order and make the sort unstable.

Try It Yourself

Reading about an algorithm only gets you so far. Here are a few quick exercises to see whether it’s really sunk in:

  1. Change the Python function so it sorts in descending order.
  2. Add counters to track how many comparisons and swaps it makes.
  3. Run the optimized version on a list that’s already sorted and see how many passes it takes.

Quick Recap

Bubble sort compares neighbouring items and swaps them when they’re out of order, pass after pass, until nothing needs swapping. It’s easy to understand, easy to write, and far too slow for big jobs. Think of it as training wheels for sorting algorithms. You won’t ride with them forever, but you’ll be glad you started there.

Once bubble sort feels comfortable, try insertion sort next, then merge sort and quick sort. The speed difference when you get away from O(n²) is surprising.

Frequently Asked Questions

What is bubble sort in simple words?
It sorts a list by repeatedly comparing two side-by-side items and swapping them if they’re in the wrong order, until the whole list is in order.

Why is it called bubble sort?
Larger values slowly “bubble” up to the end of the list on each pass, like bubbles rising through water.

What is the time complexity of bubble sort?
O(n²) on average and in the worst case. In the best case, it’s O(n), when you use the optimized version on a list that’s already sorted.

Is bubble sort good for large data?
No. The quadratic running time makes it a poor choice for big datasets. Use merge sort, quick sort, or your language’s built-in sort instead.

Is bubble sort still worth learning?
Definitely, it’s the simplest way to see how sorting works, and it comes up all the time in classes and interviews.


Found this helpful? Try coding bubble sort yourself in your favourite language, then share what you built. Practising is the fastest way to make it stick.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top