Skip to content
Code it · Find the bug

Fix the insertion sort that loses values

After it runs, some values have vanished and others appear twice.

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

def insertion_sort(arr):
    for i in range(1, len(arr)):
        j = i - 1
        while j >= 0 and arr[j] > arr[i]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = arr[i]