00:00

Bubble Sort in Java

Last updated:

Sorting means putting data into a defined order, such as ascending numbers or alphabetical names. Sorted data is easier to search (binary search needs it), to merge, to deduplicate and to present.

There are many sorting algorithms, each with its own trade-offs in speed, memory use and stability. Bubble sort is the simplest of them, and a good place to start because every step is easy to follow.

What is Bubble Sort?

Bubble Sort is a simple sorting algorithm that works by repeatedly comparing adjacent elements in an array and swapping them whenever they are in the wrong order. This process continues until the array is sorted.

How Bubble Sort Works?

Bubble sort walks through the array comparing each pair of neighbouring elements and swaps them if they are in the wrong order. After one complete pass the largest value has "bubbled" to the end of the array, where it stays. The next pass does the same for the remaining elements, and so on.

  1. Compare array[0] with array[1]; swap them if the first is larger.
  2. Move one position to the right and repeat until the end of the unsorted part.
  3. The last element of the unsorted part is now in its final place; shrink the unsorted part by one.
  4. Repeat the passes. If a whole pass makes no swap, the array is already sorted and the algorithm can stop early.

Step-by-step example: the animation below sorts [7, 3, 9, 2]. Use the buttons to play, pause or step through each comparison, or press New array to try random values.

Bubble sort, step by stepPass 1 · Comparisons 0 · Swaps 0
jj+1

Press play to start.

being comparedbeing swappedin final position
Each pass compares neighbouring values from left to right and swaps them when the left one is larger, so the largest remaining value moves to the end.

For [7, 3, 9, 2] the sort needs 3 passes, 6 comparisons and 4 swaps. With n elements the worst case needs n − 1 passes and n(n − 1)/2 comparisons.

Java program for implementation of Bubble Sort

The program keeps a swapped flag so that it stops as soon as a pass makes no swaps, and shortens each pass because the end of the array is already sorted.

BubbleSortExample.java
import java.util.Arrays;

public class BubbleSortExample {

  static void bubbleSort(int[] array) {
    int n = array.length;

    for (int i = 0; i < n - 1; i++) {
      boolean swapped = false;

      for (int j = 0; j < n - 1 - i; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          swapped = true;
        }
      }
      if (!swapped) {
        break;              // no swaps in a whole pass: the array is sorted
      }
    }
  }

  public static void main(String[] args) {
    int[] array = {40, 70, 90, 20, 80, 100, 60, 10, 30, 50};
    System.out.println("Created array elements:");
    System.out.println(Arrays.toString(array));

    bubbleSort(array);

    System.out.println();
    System.out.println("Sorted array elements:");
    System.out.println(Arrays.toString(array));
  }
}
Output
Created array elements:
[40, 70, 90, 20, 80, 100, 60, 10, 30, 50]

Sorted array elements:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Optimized Bubble Sort

A plain bubble sort always makes n − 1 passes, even when the array becomes sorted early. Two small changes avoid most of that wasted work:

  1. Stop when a pass makes no swap. If no neighbours were out of order, the whole array is sorted. (The program above already does this with its swapped flag.)
  2. Remember where the last swap happened. If the last swap in a pass was between positions j and j + 1, nothing after j + 1 moved, so everything from there to the end is already sorted. The next pass can stop at j instead of just one position earlier than before.

The second idea includes the first: a pass with no swap leaves lastSwap at 0, which ends the loop. The program below sorts a nearly sorted array with this optimized version.

OptimizedBubbleSort.java
import java.util.Arrays;

public class OptimizedBubbleSort {

  static void optimizedBubbleSort(int[] array) {
    int boundary = array.length - 1;   // array[boundary + 1 ..] is already sorted

    while (boundary > 0) {
      int lastSwap = 0;                // stays 0 if this pass makes no swap
      
      for (int j = 0; j < boundary; j++) {
        if (array[j] > array[j + 1]) {
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          lastSwap = j;                // nothing after j + 1 moved in this pass
        }
      }
      boundary = lastSwap;             // next pass stops here; 0 ends the loop
    }
  }

  public static void main(String[] args) {
    int[] array = {10, 20, 30, 50, 40, 60, 70, 80};
    System.out.println("Before sorting: " + Arrays.toString(array));

    optimizedBubbleSort(array);

    System.out.println("After sorting:  " + Arrays.toString(array));
  }
}
Output
Before sorting: [10, 20, 30, 50, 40, 60, 70, 80]
After sorting:  [10, 20, 30, 40, 50, 60, 70, 80]

Here the first pass swaps only 50 and 40, at positions 3 and 4, so the boundary drops straight from 7 to 3. The second pass compares just the first four values, finds nothing to swap and stops. That is 2 passes and 10 comparisons, where a plain bubble sort without these checks always makes 7 passes and 28 comparisons for 8 values. An already sorted array needs a single pass of n − 1 comparisons (the O(n) best case). In reverse order every pass swaps up to its last pair, so nothing can be skipped: the optimizations do not change the O(n2) worst case.

Time and Space Complexity

CaseTimeWhen it happens
BestO(n)The array is already sorted: one pass with no swaps (thanks to the swapped flag).
AverageO(n2)Random order.
WorstO(n2)Reverse order: every comparison causes a swap, n(n − 1)/2 swaps in total.

Space: O(1) extra; bubble sort sorts in place. It is stable: equal elements are never swapped, so they keep their original order.

When to Use Bubble Sort

  • Good for: small arrays, or arrays that are already almost sorted (the early-exit check makes it close to O(n)).
  • Not good for: anything large. Its O(n2) running time and many swaps make it slower in practice than insertion sort; for general sorting use Arrays.sort(), which runs in O(n log n).