In this article
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]:
| Pass | Compared pair | Swap? | Array after |
|---|---|---|---|
| 1 | 5 and 3 | Yes | [3, 5, 8, 1] |
| 1 | 5 and 8 | No | [3, 5, 8, 1] |
| 1 | 8 and 1 | Yes | [3, 5, 1, 8] |
| 2 | 3 and 5 | No | [3, 5, 1, 8] |
| 2 | 5 and 1 | Yes | [3, 1, 5, 8] |
| 3 | 3 and 1 | Yes | [1, 3, 5, 8] |

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

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 size | Comparisons in the worst case |
|---|---|
| 4 | 6 |
| 10 | 45 |
| 100 | 4,950 |
| 1,000 | 499,500 |
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.

Continue the conversation