Skip to content

3. Bubble Sort

Bubble sort is the simplest of all of the sorting algorithms. It swaps elements until everything is sorted, nothing fancy1. A good representation of each of the sorting algorithms covered can be found here.

public <T extends Comparable<? super T>> void bubbleSort(T[] array) {
    for (int i = 0; i < array.length; i++) {
        boolean swapped = false;
        for (int j = 0; j < array.length - i - 1; j++) {
            if (array[j].compareTo(array[j + 1]) > 0) {
                T temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                swapped = true;
            }
        }

        if (!swapped) {
            break;
        }
    }
}

This algorithm takes $O(n^2)$ time because it requires the transversal of two for loops. With space complexity of $O(1)$.

Next Page →


  1. For all sorting algorithms, the implementations are from Geeks for Geeks with modifications from me. Run times from Big Oh Cheat Sheet