Algorithms

Bubble sort: easy to understand, slow to run. Is it worth it?

Cover of the article Bubble sort: easy to understand, slow to run. Is it worth it?
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. Why is it called bubble sort?
  2. How does bubble sort work?
  3. Bubble sort example, step by step
  4. Bubble sort in PHP, Python and C
  5. Is bubble sort fast?
  6. Now you ask: so why learn bubble sort?
  7. Now it’s your turn!

Bubble sort is a sorting algorithm that goes through the array several times, compares two neighbors at a time and swaps them when they’re out of order. With each pass, the largest value that’s still out of place ends up at the end of the array.

In the article on binary search, you saw that it only works on a sorted array. So today we’re going to learn how to sort! But first, the answer to the challenge: to find out that 5 wasn’t in the array, binary search made 3 comparisons, with 25, 7 and 3. Did you get it right? If not, that’s okay: redo it calmly and you’ll get there.

Why is it called bubble sort?

Think of the bubbles in a glass of soda, which keep rising until they reach the top. Something similar happens in bubble sort: with each pass, the largest value “rises” through the array until it reaches the last position, like a bubble. That’s where the name comes from.

How does bubble sort work?

  • Compare the first value with the second. If the first one is larger, swap them.
  • Do the same with the second and the third, then with the third and the fourth, and so on until the end of the array.
  • When the pass is over, the largest value is in the last position.
  • Repeat, leaving aside the positions at the end that are already in place, until there’s nothing left to swap.

That’s all there is to it: compare, swap and repeat. As simple as that!

Bubble sort example, step by step

Let’s sort the array [5, 3, 8, 1]:

PassCompared pairSwap?Array after
15 and 3Yes[3, 5, 8, 1]
15 and 8No[3, 5, 8, 1]
18 and 1Yes[3, 5, 1, 8]
23 and 5No[3, 5, 1, 8]
25 and 1Yes[3, 1, 5, 8]
33 and 1Yes[1, 3, 5, 8]
Bubble sort step by step on the array [5, 3, 8, 1].
Diagram of the first pass of bubble sort on the array 5, 3, 8, 1, with the comparison and the swap decision for each pair
The first pass of bubble sort: 8, the largest value, ends up in the last position.

That took 6 comparisons to sort 4 values. Notice that in the first pass 8 went to the end, in the second it was 5’s turn, and that’s how the array gets sorted from back to front.

See the bubble sort animation, step by step
Animation of bubble sort sorting the array 5, 3, 8, 1 in three passes and six comparisons, with each compared pair highlighted
The same example in motion: three passes, six comparisons, and the array gets sorted from back to front.

Bubble sort in PHP, Python and C

Here it is in PHP:

<?php

function bubbleSort(array $numbers): array
{
    $size = count($numbers);

    for ($pass = 0; $pass < $size - 1; $pass++) {
        $swapped = false;

        for ($i = 0; $i < $size - 1 - $pass; $i++) {
            if ($numbers[$i] > $numbers[$i + 1]) {
                // swap the two neighbors
                [$numbers[$i], $numbers[$i + 1]] = [$numbers[$i + 1], $numbers[$i]];
                $swapped = true;
            }
        }

        if (!$swapped) {
            break; // no swaps: the array is already sorted
        }
    }

    return $numbers;
}

echo implode(', ', bubbleSort([5, 3, 8, 1])), PHP_EOL; // 1, 3, 5, 8

In Python:

def bubble_sort(numbers):
    size = len(numbers)

    for pass_number in range(size - 1):
        swapped = False

        for i in range(size - 1 - pass_number):
            if numbers[i] > numbers[i + 1]:
                # swap the two neighbors
                numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
                swapped = True

        if not swapped:
            break  # no swaps: the array is already sorted

    return numbers


print(bubble_sort([5, 3, 8, 1]))  # [1, 3, 5, 8]

And in C:

#include <stdio.h>

void bubble_sort(int numbers[], int size) {
    for (int pass = 0; pass < size - 1; pass++) {
        int swapped = 0;

        for (int i = 0; i < size - 1 - pass; i++) {
            if (numbers[i] > numbers[i + 1]) {
                // swap the two neighbors
                int temp = numbers[i];
                numbers[i] = numbers[i + 1];
                numbers[i + 1] = temp;
                swapped = 1;
            }
        }

        if (!swapped) {
            break; // no swaps: the array is already sorted
        }
    }
}

int main(void) {
    int numbers[] = {5, 3, 8, 1};

    bubble_sort(numbers, 4);

    for (int i = 0; i < 4; i++) {
        printf("%d ", numbers[i]); // 1 3 5 8
    }

    printf("\n");
    return 0;
}

Did you notice the swapped variable? It’s a simple trick: if a whole pass ends without a single swap, the array is already sorted, and the algorithm stops right there, without wasting time on useless passes.

Is bubble sort fast?

To be honest: no. On an array with n values, it can make up to n × (n − 1) ÷ 2 comparisons. See how quickly that number grows:

Array sizeComparisons in the worst case
46
1045
1004,950
1,000499,500
Maximum number of bubble sort comparisons as the array grows.

The array got 10 times bigger and the work got about 100 times bigger. That’s what we call O(n²) complexity. If you want to understand this notation calmly, see the article on Big O notation.

Now you ask: so why learn bubble sort?

To learn how to think! It’s a great starting point to understand what a sorting algorithm does. Once you understand bubble sort, you’re ready to understand the faster ones.

In day-to-day work, you use the sorting that the language already provides. In PHP:

<?php

$numbers = [5, 3, 8, 1];

sort($numbers);

echo implode(', ', $numbers), PHP_EOL; // 1, 3, 5, 8

And in Python:

numbers = [5, 3, 8, 1]

print(sorted(numbers))  # [1, 3, 5, 8]

PHP’s manual says that sort() uses an implementation of Quicksort. Python uses Timsort, an algorithm created for the language itself, which got an improvement called Powersort in Python 3.11. Both are much faster than bubble sort on large arrays. But now you know what’s behind a line like sort($numbers), and that makes all the difference!

Now it’s your turn!

Grab a pen and paper and sort the array [4, 2, 7, 1, 3] with bubble sort, pass by pass, counting how many swaps happen. Then change the code, in whichever language you like, so that it counts the swaps, and check your result.

Don’t copy and paste: type it, run it, get it wrong and fix it. You already have what it takes to solve it; all you need is practice. The answer comes in the next article.

Bubble sort is just the first sorting algorithm on our journey: later on, you’ll meet selection sort and insertion sort. In the next article, we start a new track, data structures, with the linked list: a way to store values in sequence that’s different from the array. See you there!

Stay confident!!!

Sources:

  • Runestone Academy, Problem Solving with Algorithms and Data Structures using Python (Brad Miller and David Ranum). 6.7 The Bubble Sort, with n − 1 passes to sort a list of size n, one comparison fewer in each pass, and the short bubble, which stops when a pass makes no exchanges.
  • Runestone Academy, Problem Solving with Algorithms and Data Structures using C++. 7.3 The Bubble Sort, with multiple passes that compare adjacent items and exchange those that are out of order, and bubble sort often seen as the most inefficient sorting method.
  • Virginia Tech, OpenDSA (Cliff Shaffer). Bubble Sort, with the inner loop that compares adjacent keys from left to right and the largest value that “bubbles” to the right end of the array, where the next pass no longer needs to look.
  • Duke University, Owen Astrachan. Bubble Sort: An Archaeological Algorithmic Analysis (SIGCSE 2003), with the early references to “sorting by exchange” and Donald Knuth’s verdict that, apart from its catchy name, the algorithm has little to recommend it (PDF).
  • Princeton University, Algorithms, 4th Edition (Robert Sedgewick and Kevin Wayne). Bubble.java, with bubble sort described as rarely useful, since on most inputs it runs much slower than insertion sort.
  • State University of New York at New Paltz. Bubble Sort, with the comparison of two neighbors, the swap when they’re in the wrong order and the total of 1 + 2 + ... + (n − 1) = n(n − 1)/2 comparisons, which is O(n²).
  • University of Toronto (Michael Guerzhoy). Bubble Sort complexity (lecture notes), with the case that needs all n − 1 passes, the sum n²/2 − n/2 and the worst case in O(n²), the same as selection sort.
  • Emory University, Oxford College, CS 171. Bubble Sort, with n − 1 comparisons in the first pass, n − 2 in the second and so on when the list is in reverse order, and the very long running time for large n.
  • PHP Manual. sort, with the note that sort(), like most of PHP’s sorting functions, is implemented with Quicksort, and the original order of equal elements kept since PHP 8.0.
  • PHP Wiki, RFC by Nikita Popov, implemented in PHP 8.0. PHP RFC: Make sorting stable, with zend_sort, the sort implementation underneath, described as a hybrid quick sort, and stability achieved by using the original order as a tiebreaker.
  • Python documentation. Sorting Techniques, with sorted() building a new sorted list from an iterable and sorts guaranteed to be stable.
  • Python Software Foundation, PyCon US 2023 (Sebastian Wild). Quicksort, Timsort, Powersort, with Timsort as the Mergesort variant that Tim Peters invented for CPython and the Powersort merge policy, part of CPython since Python 3.11.0.
  • University of Liverpool. Liverpool computer scientists improve Python sorting function, with Powersort, implemented in Python 3.11 after a study of the merge policy of TimSort, the sorting algorithm invented by Tim Peters.
  • The examples in this article were run on Python 3.13, PHP 8.3 and GCC 13.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

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

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).