Back

Bubble Sort

Loading controls...
Loading visualization...
Time: O(n²)
Space: O(1)

Legend

Comparing
Elements being compared
Swapping
Elements being swapped
Sorted
Elements in final position
Unsorted
Elements not yet processed
How to read the visualization:
  • • Numbers show element values
  • • Bottom labels show array indices
  • • Colors indicate current operation
  • • Height represents value magnitude

Inspector

No active frame to inspect

Reference implementation of Bubble Sort. Select a language tab to view and copy the code.

def bubble_sort(arr: list[int]) -> None:
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

Python — Code Walkthrough

  1. Type hints

    arr: list[int]) -> None

    PEP 484 annotations. The function modifies the list in-place and returns nothing (None). Lists in Python are mutable objects passed by reference, so the original list is sorted directly.

  2. Getting the length

    n = len(arr)

    Python's built-in len() returns the number of elements. Caching it in n avoids calling len(arr) on every loop iteration.

  3. range() instead of a C-style counter

    for i in range(n - 1)

    range(n − 1) generates integers 0 through n−2 inclusive. No explicit initialisation, condition, or increment needed — Python handles it idiomatically.

  4. Shrinking inner range

    for j in range(n - i - 1)

    Each outer iteration reduces the inner range by one, skipping the already-sorted elements at the tail end of the list.

  5. Tuple swap — no temp variable

    arr[j], arr[j + 1] = arr[j + 1], arr[j]

    Python's simultaneous assignment evaluates both right-hand side values before any assignment occurs. This means no temporary variable is needed — the cleanest swap of all five languages.