Python bubble sort

Each pass compares neighboring values and swaps an inverted pair. After a full pass, the largest value in the unsorted prefix is in its final position.

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

print(bubble_sort([3, 2, 1]))
assert bubble_sort([]) == []
assert bubble_sort([1, 1, 2]) == [1, 1, 2]
Read the full lesson