Skip to content

Bubble Sort ​

Bubble sort is a sort that repeatedly compares two neighboring values and swaps them if they are in the wrong order. It is the most intuitive of the sorting algorithms.

At a Glance ​

  • Similar to selection sort, it sorts by comparing the sizes of two adjacent elements and swapping them if they do not meet the condition.
  • The name comes from the way large values move up one position at a time during sorting, like bubbles rising to the surface.
  • Analogy: when lining people up by height, each person compares heights only with the person next to them, and the taller one moves back; this is repeated over and over. After one full pass, the tallest person ends up at the very back.
  • In terms of classification, it is a comparison sort (sorts by comparing values), a stable sort (equal values keep their original order) and an in-place sort (only swaps positions within the array).

How It Works ​

This is for sorting in ascending order.

  1. In pass 1, compare the first and second elements, the second and third, the third and fourth, and so on up to the (last-1)th and last elements, swapping them whenever they are out of order.
  2. When pass 1 ends, the largest element has moved to the end. So pass 2 compares everything except the last element, and after pass 2, the second-to-last element is excluded too. In this way, one more element is excluded from sorting with each pass.

Let's follow along with the example array [4, 2, 5, 1].

PassTwo values comparedArray stateExplanation
Start-[4, 2, 5, 1]Initial state
Pass 14, 2[2, 4, 5, 1]4 is larger, so swap
Pass 14, 5[2, 4, 5, 1]In order, so leave as is
Pass 15, 1[2, 4, 1, 5]Swap. The largest value 5 is fixed at the end
Pass 22, 4[2, 4, 1, 5]Leave as is
Pass 24, 1[2, 1, 4, 5]Swap. 4 is fixed
Pass 32, 1[1, 2, 4, 5]Swap. Sorting complete

In Pictures ​

Bubble sort in action

Image source: GimunLee/tech-refrigerator (Apache-2.0)

Python Code ​

python
def bubble_sort(arr):
    """Bubble sort that compares two adjacent values and moves the larger one back (ascending)"""
    n = len(arr)
    for i in range(n - 1):                 # 1.
        for j in range(1, n - i):          # 2.
            if arr[j - 1] > arr[j]:        # 3.
                arr[j - 1], arr[j] = arr[j], arr[j - 1]
    return arr


print(bubble_sort([4, 2, 5, 1]))
# Output: [1, 2, 4, 5]
  1. i is the number of elements already fixed at the back and excluded from sorting. At the end of each pass, the largest element lands in the last position, so it increases by one. The last remaining element has nothing to compare with, so n - 1 passes are enough.
  2. This loop chooses the positions to compare. j points to the current element and j - 1 to the one right before it, so j starts at 1. The last i elements are already fixed, so it only looks up to just before n - i.
  3. Compare the sizes of the two elements. Since the order is ascending, if the front element is larger it must move back, so they swap places. In Python, you can swap with a single line, a, b = b, a.

Improved Bubble Sort ​

The original source said, "There is also an improved bubble sort, but since this is a basics study, we will skip it." The improvement idea is simple: if there was not a single swap during a pass, the sort is already finished, so you can stop right away.

python
def bubble_sort_early_exit(arr):
    """Bubble sort that stops early if there are no swaps"""
    n = len(arr)
    for i in range(n - 1):
        swapped = False                    # 1.
        for j in range(1, n - i):
            if arr[j - 1] > arr[j]:
                arr[j - 1], arr[j] = arr[j], arr[j - 1]
                swapped = True             # 2.
        if not swapped:                    # 3.
            break
    return arr


print(bubble_sort_early_exit([1, 2, 3, 5, 4]))
# Output: [1, 2, 3, 4, 5]
  1. A flag that records whether any swap happened in this pass.
  2. If even one swap happens, it is set to True.
  3. If a full pass finishes with no swaps, every neighboring pair is already in order, so the loop ends.

Time and Space Complexity ​

The number of comparisons is (n-1) + (n-2) + ... + 2 + 1 = n(n-1)/2, so it is O(n²). Basic bubble sort compares every neighboring pair the same way whether or not the array is already sorted, so the best, average and worst cases are all O(n²). (Reading about Big-O notation in the time complexity article first makes this easier to understand.)

CaseBasic bubble sortImproved bubble sort
Best (already sorted)O(n²)O(n)
AverageO(n²)O(n²)
Worst (sorted in reverse)O(n²)O(n²)
SpaceExtra memory O(1) (O(n) including input)Extra memory O(1) (O(n) including input)
  • The improved version stops after a single pass (n-1 comparisons) if the array is already sorted, so its best case becomes O(n).
  • Space: it only swaps within the given array, so the extra memory beyond the input array is about one variable for swapping, O(1).

Pros and Cons ​

Pros ​

  • It is very simple to implement and the code is intuitive.
  • It swaps within the array being sorted, so it needs no other memory space. → In-place sorting
  • It is a stable sort. It swaps only when the front value is larger, so equal values never change order.

Cons ​

  • The basic version is O(n²) in the best, average and worst cases, which makes it very inefficient.
  • An unsorted element has to move one position at a time to reach its place, so many swaps occur.

Wrapping Up ​

We looked at bubble sort, the most intuitive of the sorting algorithms. It comes up fairly often in technical interviews, so it is good to know. Comparing it with selection sort, which reduces the number of swaps, makes the difference clear.

Summary ​

ConceptPlain-language summary
Bubble sortRepeatedly compare with the neighbor and push the larger value back
Result of one passEach full pass fixes the largest value at the end
Improved bubble sortStop immediately if a whole pass makes no swaps
Stable sortEqual values stay in their original order

Source: GimunLee/tech-refrigerator (Apache-2.0), code rewritten in Python

Reference: zeddios - Bubble Sort