Beginner 13 min

Bubble sort

Sort an array through adjacent comparisons and see why each pass fixes one position.

Bubble sort
bubble_sort.py
for end in range(len(values) - 1, 0, -1):
for index in range(end):
if values[index] > values[index + 1]:
values[index], values[index + 1] = values[index + 1], values[index]
return values
CURRENT STATE
70
31
52
23
64
Pass 1
Start pass 1

Compare adjacent values up to index 4.

Step 1 / 21

Compare neighbors

Start with the first two values and swap when the left value is larger. Move one position right and repeat. In a complete pass, the largest value in the unsorted range moves to the end of that range.

How it works

In one pass, compare neighbors left to right. If a bigger value appears before a smaller one, swap them. By the end of the pass the largest remaining value has reached the end. Repeat over the part that still needs sorting.

Shrink the next pass

Once the final value is in position, skip it on the next pass. If a full pass performs no swaps, the array is already ordered. With this early exit, a sorted array takes O(n) time, while reverse order takes O(n²). The algorithm uses O(1) extra space and remains stable when equal items never swap.

Code example

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

print(bubble_sort([5, 2, 4, 1]))

Check your understanding

Show the array after exactly one full pass of bubble sort, starting on the left.

See the example and explanation
Example 1
Given [4, 2, 6, 1]
Answer [2, 4, 1, 6]
Example 2
Given [1, 2, 3]
Answer [1, 2, 3]

For [4, 2, 6, 1], swap 4 and 2, keep 4 and 6, then swap 6 and 1. Only 6 is guaranteed to be in its final position after this pass.

Open practice problem
Next lessonStacks and undo