Sorting
Bubble sort
Problem statement
Given an array of n values, arrange them in ascending order.
Efficient solution idea
Compare adjacent values and swap any pair that is out of order. Each pass places the largest remaining value at the end; stop early if a pass makes no swaps.
Loading visualization…
Step-by-step approach
- Let n be the number of values. Start with the whole array as the unsorted region.
- At the beginning of each pass, set swapped = false and scan adjacent pairs from left to right within the unsorted region.
- If A[j] > A[j + 1], swap the two values and set swapped = true. Otherwise, leave the pair unchanged.
- After the pass, the largest value in the unsorted region is in its final position. Exclude that position from the next pass.
- If the pass made no swaps, stop early. Otherwise, repeat until at most one unsorted value remains.
- Return the array in ascending order.
Keep in mind: The suffix after the last compared position is sorted.
O(n²) worst, O(n) best; O(1) auxiliary space.
Pseudocode
bubbleSort(A, n)
for end from n - 1 down to 1
swapped = false
// Compare adjacent values in the unsorted part
for j from 0 to end - 1
if A[j] > A[j + 1]
swap(A[j], A[j + 1])
swapped = true
// No swaps means the array is already sorted
if swapped == false
break
return AExplore edge cases
To explore a case, enter its values in Input settings and press Play.
Already sorted
One pass is enough to detect that no swaps are needed.
1, 2, 3, 4, 5, 6All equal
Equal neighbors are never swapped.
4, 4, 4, 4, 4, 4Similar problems
- Count inversions
Count how many pairs are out of order; relate swaps and merging to disorder.
- Compare elementary sorting algorithms
Compare how adjacent swaps, insertion and minimum selection grow a sorted region.
- Merge sort
Combine sorted subproblems while preserving equal-value order.

