Algorithm

Take a list of length .

We can iterate through adjacent pairs in the loop, and swap those out of order. Performing this times, we can guarantee that the final values are correct (and sorted) - the below example illustrates why.

  1. For the first iteration,

  2. For the second iteration,

  3. For the third iteration,

We are done! Notice how in every iteration (starting from 1) of the loop, we guarantee the index of the loop correctly contains the largest element. Thus, performing this times, we can guarantee a sorted array (if all elements are sorted, the first element must be the smallest element).

Pseudocode

Pseudocode for Bubble Sort is given below.

def bubble_sort(array):
    # i only needs to iterate n - 1 times
    for i in range(0, len(array) - 1):
        # we don't need to check / sort the ith last
        # elements of the array, as they're already sorted
        for j in range(0, n - i - 1):
            # swap the elements if not sorted
            if array[j] > array[j + 1]:
               temp = array[j]
               array[j] = array[j + 1]
               array[j + 1] = temp

We find the time complexity of Bubble Sort to be , and the auxilliary memory to be (no extra memory). This implementation of Bubble Sort is stable and in-place.

It’s worth noting that regardless if the list is sorted, Bubble Sort always takes the same amount of time.

Bubble Sort Stability

While this implementation of Bubble sort is stable, that does not mean all implementations necessarily are. If we replaced the in line 8 with , we would make our algorithm unstable!