Skip to content
Bubble sort

Bubble sort.

Time (worst)
O(n²)
Space
O(1)

Compare two neighbors. Swap if needed. Watch the biggest move right.

Why learn bubble sort?

Bubble sort is a simple way to understand sorting. Look at two numbers next to each other. If the left one is bigger, swap them. Keep going, then start again from the left. It is useful for learning, but it needs many comparisons on large lists, so faster sorting algorithms are usually a better choice for those.

Customize input

Smallest → biggest

0 comparisons · 0 swaps · This pass: 0 swaps

Start

Put the numbers in order

Sorting means putting numbers in order. We want smallest to biggest. Check two numbers next to each other; swap them only if the left one is bigger.

Check two neighbors, then move one position right
6
3
8
2
5
i: 0i: 1i: 2i: 3i: 4

Use Next for one action, or Play to watch. Drag the timeline to preview silently.

Voice is unavailable in this browser. Follow the explanations above.

Follow the logic

Python
def bubble_sort(a):    for end in range(len(a) - 1, 0, -1):        swapped = False        for j in range(end):            if a[j] > a[j + 1]:                a[j], a[j + 1] = a[j + 1], a[j]                swapped = True        if not swapped:            break    return a

n is the number of items. Best-case time: O(n) for an already sorted list, because this version stops after a pass with no swaps. Equal values keep their original order. O(1) space describes the algorithm; the visualizer stores extra snapshots so you can rewind.