Back

Bubble Sort

2024-05-02

Written by: Juri Breslauer

Algorithm Notes

Bubble sort, one neighbor at a time

Bubble sort compares two neighboring values. If the left value is bigger, they swap places. After each pass, the largest unsorted value has moved to the right side.

Interactive demo

Bubble sort demo

Ready
Pass 1
Compare 0
Swaps 0

Why It Looks Like This

The animation uses a small set of bars as an example. On every step, bubble sort looks at two neighbors:

Complexity

Bubble sort is easy to understand, but it is not efficient for large inputs. In the average and worst case it needs O(n²) comparisons. That is fine for a small visual demo. For thousands of items, a better sorting algorithm is usually the right choice.

Here are examples of the same bubble sort algorithm in different programming languages.