Bubble Sort

Visualize bubble sort step by step - watch adjacent comparisons and swaps animate in real time.

About Bubble Sort

How Bubble Sort Works

Bubble sort repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This pass-through is repeated until the list is sorted. It is one of the simplest sorting algorithms to understand and implement.

Starting from the first element, compare each pair of adjacent elements and swap them if the left one is greater. After each full pass, the largest unsorted element 'bubbles up' to its correct position. Repeat until no swaps are needed.

Complexity

Time
O(n²)
Space
O(1)
Stability
stable

When to Use Bubble Sort

  • Educational purposes and learning to sort
  • Nearly sorted small datasets
  • When simplicity matters more than speed

Implementation

1def bubble_sort(arr) -> list[int]:
2    if arr is None or len(arr) == 0:
3        raise ValueError("Array is empty")
4    for step in range(len(arr)):
5        for i in range(len(arr) - 1 - step):
6            if arr[i] > arr[i + 1]:
7                arr[i], arr[i + 1] = arr[i + 1], arr[i]
8    return arr
9

Bubble Sort Animation

Waiting for input...

No steps to display. Please provide input to visualize the algorithm.

-