Bubble Sort in Java
Learn how Bubble Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Bubble Sort is a simple comparison sort. It walks through the array again and again, compares each pair of neighbours, and swaps them when they are in the wrong order. After each walk, the largest value that is not yet in place has “bubbled up” to the end of the array.
Three ideas carry the whole algorithm:
- Neighbours: each comparison looks at two adjacent elements,
array[j]andarray[j + 1], and swaps them if the left one is larger. - Pass: one walk from the start of the array to the end of the unsorted part. Every pass puts one more value in its final position at the end.
- Early exit: if a whole pass makes no swaps, every neighbour is in order, so the array is sorted and the algorithm stops.
Bubble Sort is usually the first sorting algorithm people learn, because it is short and easy to trace by hand. It is rarely used in practice: insertion sort does the same job with fewer swaps, and $O(n \log n)$ sorts such as QuickSort and Merge Sort are far faster on anything but tiny arrays.
This article uses the optimised Bubble Sort: each pass stops one position earlier than the one before it, and the sort stops as soon as a pass makes no swaps.
Performance Characteristics
Bubble Sort needs almost no extra memory, but its speed depends heavily on how far the input is from sorted: a sorted array takes one pass, a reversed one takes every pass.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | The array is already sorted: one pass with no swaps |
| Average | $O(n^2)$ | Random or mixed input |
| Worst | $O(n^2)$ | The array is in reverse order: every comparison leads to a swap |
Why $n^2$? There can be up to $n - 1$ passes, and pass $i$ compares $n - i$ pairs. That adds up to $\frac{n(n-1)}{2}$ comparisons, which grows with $n^2$.
The best case of $O(n)$ only exists because of the
swappedflag. Without it, Bubble Sort makes all $\frac{n(n-1)}{2}$ comparisons even when the array is already sorted.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(1)$: only a few loop variables and a flag |
| In place | Yes |
| Stable | Yes (equal neighbours are never swapped) |
Algorithm (Pseudo Code)
Bubble Sort starts at the beginning of the array and compares the first two values. If the left one is larger, they swap places. Then it moves one step to the right and compares the next pair, and so on until the end of the array. The largest value is picked up by every comparison along the way, so at the end of this first pass it sits in the last position, where it belongs.
The next pass does the same, but stops one position earlier, because the last value is already in place. Each pass settles one more value at the end, so the sorted part grows from the right while the unsorted part shrinks. If a pass gets all the way through without a single swap, every value is already next to the right neighbours, and the array is sorted.
1
2
3
4
5
6
7
8
9
10
sort(array):
for i = 1 to n - 1:
swapped = false
for j = 0 to n - i - 1:
if array[j] > array[j + 1]:
swap(array[j], array[j + 1])
swapped = true
if not swapped:
break // no swaps: already sorted
return array
After pass i, the last i positions hold the i largest values, in their final sorted order.
The comparison is strict: neighbours are swapped only when the left value is greater, never when they are equal. Equal values therefore never pass each other, which is what makes Bubble Sort stable.
Visualization
The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.
Each step shows the array, the pair being compared and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Pointers: J is
j, the left value of the pair, and J+1 is the right value it is compared with. - Colours: the two values being compared are amber, the two values being swapped are salmon, and values in their final position turn green.
- Boundary: the gray bar marks where the sorted part starts. Each pass stops just before it.
- Pass: the footer shows the current pass
iand the value of theswappedflag.
Java Code
The implementation is a BubbleSort class with a single public method, sort, which holds both loops: the outer loop counts the passes and the inner loop compares and swaps neighbours. Two small helpers, greater and swap, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
BubbleSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 1, size = array.length; i < size; ++i) {
boolean swapped = false;
for (int j = 0; j < size - i; ++j) {
if (SortUtils.greater(array[j], array[j + 1])) {
SortUtils.swap(array, j, j + 1);
swapped = true;
}
}
if (!swapped) {
break;
}
}
return array;
}
sort is the entry point and the whole algorithm. It accepts an array of any Comparable type, such as Integer or String, and sorts it in place. The outer loop runs one pass per value of i. The inner loop walks j from 0 up to the end of the unsorted part, and swaps array[j] and array[j + 1] whenever the left one is greater. If a pass ends with swapped still false, the loop stops early. The method returns the same array, now sorted.
Two details are worth noticing:
istarts at1and counts the passes, so after passithe lastipositions are final. That is why the inner loop stops atsize - i: it never compares values that are already in place, andj + 1never runs past the end of the array.sizeis declared in theforstatement next toi, soarray.lengthis read once instead of on every pass.
greater and swap
1
2
3
4
5
6
7
8
9
10
11
public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) > 0;
}
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
These two helpers from SortUtils keep sort easy to read. greater returns true when the first element is larger than the second, using compareTo, so the algorithm works for any type that implements Comparable. Because it is a strict comparison, equal neighbours are never swapped. swap exchanges two elements, and skips the work when both indices are the same.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new BubbleSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a BubbleSort, pass it an array, and the same array comes back sorted. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Bubble Sort is a simple comparison sort: it compares neighbours and swaps them when they are in the wrong order, one pass at a time.
- This implementation is the optimised version: each pass stops one position earlier, and a
swappedflag gives an early exit when a pass makes no swaps. - After pass
i, the lastipositions hold theilargest values in their final order. - It runs in $O(n)$ on an already sorted array and $O(n^2)$ on average and in the worst case, with only $O(1)$ extra space.
- It is stable and sorts in place, but it is slow. For small or nearly sorted arrays, insertion sort is a better simple choice; for anything larger, use an $O(n \log n)$ sort such as QuickSort or Merge Sort.
