Bubble Sort

Sort an array by swapping neighbouring values that are out of order, one pass at a time, until a pass makes no swaps.

Given an array of integers, sort it in ascending order with bubble sort. Walk through the array, compare each value with its right-hand neighbour, and swap the two when the left one is bigger. Change the given array itself rather than returning a new one.

Example
Input: [5, 1, 4, 2, 8]
Output: [1, 2, 4, 5, 8]
Solution

The Idea

Picture five number cards in a row: 5, 1, 4, 2 and 8. You want them in order, but you may only swap two cards that lie next to each other. Where do you start?

Start on the left. 5 is bigger than 1, so swap them, which gives 1, 5, 4, 2, 8. Now compare the 5 with its new neighbour, 4: swap again. Then 5 and 2: swap once more. Last, 5 and 8 are already in order, so they stay. One walk from the left end to the right end like this is called a pass.

The picture below shows the cards after each pass. Look at the row labelled "after pass 1": the 5, in orange, travelled three places to the right, one swap at a time, and stopped when it met 8. Once a pass reaches the largest value, every later comparison pushes that value one more step right. So the largest value always ends the pass in the last place, here the 8. Large values rise to the end like bubbles in water, which is where the name bubble sort comes from.

Bubble sort on 5, 1, 4, 2, 8. After pass 1 the array is 1, 4, 2, 5, 8 with 8 in its final place. After pass 2 it is 1, 2, 4, 5, 8. Pass 3 makes no swaps, so the sort stops.

So each pass puts one more value in its final place, shown in teal. In the row labelled "after pass 2", the 4 moved past the 2, and the 5 turned teal beside the 8. That raises two questions: how far does each pass still need to walk, and when is the sorting done?

After pass 2 the cards read 1, 2, 4, 5, 8, already in order. The sort cannot know that yet, since it only ever looks at two neighbours. Pass 3 compares 1 with 2 and 2 with 4, and swaps nothing. That is the signal to stop. If no neighbour pair is out of order, every value is at most the one to its right, and the whole row is sorted.

Solution Approach

Four things need deciding: how far each pass walks, when to stop, what to do with two equal neighbours, and where the sorted values are kept.

How far each pass walks

How many neighbour pairs does a pass have to check? The plainest version walks the whole array every time and makes n - 1 passes, where n is the number of values. That always sorts the array, because after n - 1 passes the n - 1 largest values are in their final places, and the value left over at the front is the smallest.

That plain version keeps comparing the teal values, which can no longer move. After pass 1 the last value is final, after pass 2 the last two, and so on. So each pass can stop one pair earlier than the pass before it. In the picture, the three passes compare 4, 3 and 2 pairs.

Stopping after a pass with no swaps

When can the sort stop before all n - 1 passes? As soon as a pass swaps nothing, as pass 3 did. A boolean flag set to false at the start of each pass, and to true on every swap, tells whether that happened. For input that is already sorted, the first pass finds no swap and the sort ends there.

Equal neighbours

What should happen when two neighbours are equal? Swap only when the left value is strictly bigger, so two equal values never trade places. Think of sorting the words pear, fig, kiwi, plum and ash by their length. A sort that returns fig, ash, pear, kiwi, plum, with equal-length words still in their input order, is called stable.

Stability matters when the sort compares only part of each item, like a word's length. With plain numbers you cannot tell two equal values apart, so the order between them does not show.

Sorting inside the given array

Where do the sorted values go? Each swap trades two values inside the given array, through one temporary variable, so no second array is needed. A sort that rearranges its input this way, using only a fixed amount of extra memory, is called in place.

Java Solution

The method sort works in these steps:

  1. First, store the length of the input array arr in n, and start a counter comparisons at 0.
  2. An outer loop counts the passes with i, from 0 while i < n - 1, so there are at most n - 1 passes. At the start of each pass, a flag named swapped is set to false.
  3. Inside, a second loop moves j from 0 while j < n - i - 1, because the last i places already hold their final values. For each j, it adds 1 to comparisons and compares arr[j] with arr[j + 1].
  4. When arr[j] is strictly bigger, swap the two values through a temporary variable tmp and set swapped to true.
  5. After the second loop, if swapped is still false, the pass found every pair in order, so break ends the outer loop.
  6. Return the count held in comparisons. The sort does not need this count, but it lets main show how much work each input takes.

A second method, sortByLength, runs the same two loops on an array of words but compares their lengths, to show stability. A helper, show, prints an array before and after sorting, with the number of comparisons.

The main method sorts the example, the same values already sorted and in reverse order, an array with repeats, one value and an empty array. Then it sorts the five words by length. Last, it sorts 1,000 numbers that are sorted, random and reversed. The random ones come from a Random seeded with 42, so every run prints the same.

Java
import java.util.Arrays;
import java.util.Random;

public class BubbleSort {

    // Sorts arr in ascending order and returns how many comparisons it made.
    public static long sort(int[] arr) {
        long comparisons = 0;
        int n = arr.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - i - 1; j++) {   // the last i places are already final
                comparisons++;
                if (arr[j] > arr[j + 1]) {          // strict >: equal values stay in order
                    int tmp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break;                              // a pass with no swaps: sorted
            }
        }
        return comparisons;
    }

    // The same loops, comparing words by length only, to show that the sort is stable.
    public static void sortByLength(String[] words) {
        int n = words.length;
        for (int i = 0; i < n - 1; i++) {
            boolean swapped = false;
            for (int j = 0; j < n - i - 1; j++) {
                if (words[j].length() > words[j + 1].length()) {
                    String tmp = words[j];
                    words[j] = words[j + 1];
                    words[j + 1] = tmp;
                    swapped = true;
                }
            }
            if (!swapped) {
                break;
            }
        }
    }

    static void show(int[] arr) {
        String before = Arrays.toString(arr);
        long comparisons = sort(arr);
        System.out.println(before + " -> " + Arrays.toString(arr)
                + ", comparisons: " + comparisons);
    }

    public static void main(String[] args) {
        show(new int[] {5, 1, 4, 2, 8});
        show(new int[] {1, 2, 4, 5, 8});
        show(new int[] {8, 5, 4, 2, 1});
        show(new int[] {3, 1, 3, 1});
        show(new int[] {7});
        show(new int[] {});

        String[] words = {"pear", "fig", "kiwi", "plum", "ash"};
        sortByLength(words);
        System.out.println(Arrays.toString(words));

        int n = 1000;
        int[] sorted = new int[n];
        int[] reversed = new int[n];
        int[] random = new int[n];
        Random rnd = new Random(42);
        for (int k = 0; k < n; k++) {
            sorted[k] = k;
            reversed[k] = n - k;
            random[k] = rnd.nextInt(n);
        }
        System.out.println("1000 sorted:   " + sort(sorted) + " comparisons");
        System.out.println("1000 random:   " + sort(random) + " comparisons");
        System.out.println("1000 reversed: " + sort(reversed) + " comparisons");
    }
}

Running it prints:

Output
[5, 1, 4, 2, 8] -> [1, 2, 4, 5, 8], comparisons: 9
[1, 2, 4, 5, 8] -> [1, 2, 4, 5, 8], comparisons: 4
[8, 5, 4, 2, 1] -> [1, 2, 4, 5, 8], comparisons: 10
[3, 1, 3, 1] -> [1, 1, 3, 3], comparisons: 6
[7] -> [7], comparisons: 0
[] -> [], comparisons: 0
[fig, ash, pear, kiwi, plum]
1000 sorted:   999 comparisons
1000 random:   499004 comparisons
1000 reversed: 499500 comparisons

Sorting [5, 1, 4, 2, 8] took 9 comparisons, the 4, 3 and 2 written next to the passes in the picture. The same values already in order need only 4, one pass with no swap. In reverse order, [8, 5, 4, 2, 1] needs 10, every pair of all four passes. The input [3, 1, 3, 1] shows that repeated values sort fine, and [7] and [] make 0 comparisons because the outer loop never starts.

Now look at the words line, [fig, ash, pear, kiwi, plum]. The three-letter words and the four-letter words each kept their input order, so the sort is stable. A separate run of the same loops with >= in place of > printed [ash, fig, plum, kiwi, pear], with the equal-length words reversed.

The last three lines show the cost growing. Sorted, 1,000 numbers take 999 comparisons, a single pass. Reversed, they take 499,500, which is 1000 × 999 / 2. The random numbers take 499,004, nearly as many as the reversed ones, so the early stop saves little unless the input is close to sorted.

Complexity

How sorted the input already is decides the number of passes, and each pass compares a shrinking run of pairs.

  • Best time: O(n), for input that is already sorted, because the first pass makes n - 1 comparisons, finds no swap and stops, as the 999 comparisons for 1,000 sorted numbers show.
  • Worst time: O(n2), for input in reverse order, because the smallest value moves only one place left per pass, so all n - 1 passes run and compare n(n - 1)/2 pairs.
  • Average time: O(n2), for input in random order, because among n random values some small one usually starts near the end, and it needs nearly every pass to reach the front, as 499,004 comparisons for 1,000 random numbers show.
  • Space: O(1), because the swaps happen inside the given array, and the sort keeps only the two loop counters, the flag and one temporary value.

For larger arrays, a sort that splits the work into halves takes O(n log n) time instead: see Merge Sort.