AlgoTales · Roadmap

Bubble sort

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Bubble sort walks along a list comparing neighbours and swapping any pair that is in the wrong order, repeating until a whole walk needs no swaps. It is slow on big lists, but it is easy to understand and is a good way to learn what sorting really does.

Practical use cases

  • Web app: Sorting a tiny dropdown list. A settings page shows 8 country codes that must appear alphabetically in a dropdown. For a list that small, a simple swap-neighbours loop is more than fast enough, and the code is short enough for a new teammate to read and trust in one minute.
  • Web app: Nearly sorted table. A table of 40 rows is almost always in order, with only one or two rows out of place after an edit. Bubble sort stops after a pass with no swaps, so on nearly sorted data it finishes after a pass or two. The page tidies itself without any heavy work.
  • System: Teaching and warning example. Bubble sort is the classic classroom example, and also the classic warning: on 1 lakh rows it would do billions of comparisons. Seeing it crawl on large data is what makes developers trust the built-in sort functions instead of writing their own.

The story: Lining Up by Height

Mrs. Sharma told the class: "Line up from shortest to tallest!" Chaos followed. So she gave one simple rule: look only at the child next to you. If the left one is taller than the right one, swap places. Otherwise stay.

Kids swapped in pairs, up and down the line. After the first sweep, something magical: the tallest child had "bubbled" all the way to the end of the line, because every time they met someone shorter, they swapped forward.

Sweep again, and the second-tallest settles into their spot. Keep sweeping and the line becomes perfectly ordered. When a full sweep happens with no swaps at all, Mrs. Sharma knew the job was done, and the class went out to play.

How to spot this problem, and where you need it

You need to put a very small or almost-sorted list in order and want the simplest possible code, or you need to understand how sorting works before using faster methods.

Signs you need it

  • The list has only a handful of items, such as menu entries or dropdown options, and speed is not a concern.
  • The data is already nearly in order and just one or two items are out of place after an update.
  • You find yourself writing a nested loop that swaps neighbours, and the page slows down badly once the list passes a few thousand rows.

Where to use it in a project

  • Learning exercises and interviews that ask you to show how sorting works step by step.
  • Tiny lists in UI code where the built-in sort would be overkill, and as a cautionary example of what not to use on big data.

The solution

Go along the list comparing each item with the next one. If they are in the wrong order, swap them. At the end of the pass, the biggest item has floated to the end, so the next pass can stop one place earlier. Repeat, and if a whole pass makes no swaps, the list is sorted and you can stop early. For real apps with big lists, use the language sort instead.

Payoff: For 10 items it takes a few dozen steps and no thought. For 1 lakh items it would take billions, which is why you switch to a proper sort.

Explain it like I am 8

It is like bubbles in a soda: the biggest bubble floats to the top first. You compare two neighbours at a time. If they are in the wrong order, swap them. Keep walking along the line until nobody needs to swap.

How it works, step by step

  1. Compare two neighbours. Is the left one bigger than the right one?
  2. Swap if yes. Otherwise leave them.
  3. Finish one sweep. The biggest unsorted item is now locked into its final place at the end.
  4. Repeat the sweeps over what is left. If a sweep has no swaps, stop early. You are sorted.

The code in four languages

PHP

<?php
function bubbleSort(array $a): array {
    $n = count($a);
    for ($pass = 0; $pass < $n - 1; $pass++) {
        $swapped = false;
        for ($i = 0; $i < $n - 1 - $pass; $i++) {   // last $pass items are already home
            if ($a[$i] > $a[$i + 1]) {
                [$a[$i], $a[$i + 1]] = [$a[$i + 1], $a[$i]];   // swap neighbours
                $swapped = true;
            }
        }
        if (!$swapped) break;                       // no swaps: already sorted!
    }
    return $a;
}

print_r(bubbleSort([5, 1, 4, 2, 8]));               // [1, 2, 4, 5, 8]

JavaScript

function bubbleSort(arr) {
  const a = [...arr];
  const n = a.length;
  for (let pass = 0; pass < n - 1; pass++) {
    let swapped = false;
    for (let i = 0; i < n - 1 - pass; i++) {        // last "pass" items are already home
      if (a[i] > a[i + 1]) {
        [a[i], a[i + 1]] = [a[i + 1], a[i]];        // swap neighbours
        swapped = true;
      }
    }
    if (!swapped) break;                            // no swaps: already sorted!
  }
  return a;
}

console.log(bubbleSort([5, 1, 4, 2, 8]));           // [1, 2, 4, 5, 8]

Java

import java.util.*;

public class Main {
    static int[] bubbleSort(int[] arr) {
        int[] a = arr.clone();                              // work on a copy
        int n = a.length;
        for (int pass = 0; pass < n - 1; pass++) {
            boolean swapped = false;
            for (int i = 0; i < n - 1 - pass; i++) {        // last "pass" items are already home
                if (a[i] > a[i + 1]) {
                    int tmp = a[i];                         // swap neighbours
                    a[i] = a[i + 1];
                    a[i + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) break;                            // no swaps: already sorted!
        }
        return a;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(bubbleSort(new int[]{5, 1, 4, 2, 8})));   // [1, 2, 4, 5, 8]
    }
}

Go

package main

import (
	"fmt"
	"slices"
)

func bubbleSort(arr []int) []int {
	a := slices.Clone(arr) // work on a copy
	n := len(a)
	for pass := 0; pass < n-1; pass++ {
		swapped := false
		for i := 0; i < n-1-pass; i++ { // last "pass" items are already home
			if a[i] > a[i+1] {
				a[i], a[i+1] = a[i+1], a[i] // swap neighbours
				swapped = true
			}
		}
		if !swapped {
			break // no swaps: already sorted!
		}
	}
	return a
}

func main() {
	fmt.Println(bubbleSort([]int{5, 1, 4, 2, 8})) // [1 2 4 5 8]
}

Time: Worst O(n²) · Best O(n) · Extra space: O(1). Stable and in-place. Best case O(n) only with the early-exit "swapped" flag.

Watch out for

  • Forgetting the early-exit flag, which makes even a sorted list cost O(n²).
  • Re-checking items that are already in place. Shrink the inner loop each pass.

Quick check

  1. After the first full sweep, what is in the last position?
    • The smallest item
    • The largest item
    • A random item
  2. A sweep finishes with zero swaps. What does that mean?
    • The list is sorted
    • Something went wrong
    • Start again
  3. Worst-case time of bubble sort?
    • O(n)
    • O(n log n)
    • O(n²)