Bubble sort
Sort an array through adjacent comparisons and see why each pass fixes one position.
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 valuesCompare adjacent values up to index 4.
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.