Skip to content
Code it · Find the bug

Fix the crashing bubble sort

It crashes with an index error on its very first pass.

Run it, watch what it really does on the array, and fix it. One small change is enough.

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]