Big O Gym › Problem

Big O Practice: Insertion Sort

Time and space complexity practice in Python and JavaScript. Concept tested: shifting prior elements one slot at a time.

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

Variables

  • n - length of the input array

Explanation

Outer loop runs `n` times; inner loop shifts up to all prior elements. Worst case (reverse-sorted) hits **O(n²)** time - that is the answer to give unless the question explicitly asks for best case (which is O(n) on already-sorted input). Shifts happen in place, **O(1)** space.

More Big O practice problems · Today's daily problem