Sorting

Problem shape

Beginner
4
8
15
16
23
42
Core idea

Grow a sorted prefix by inserting each new value into its correct place.

Step 1 / 5
Problem shape
Current lesson

Insertion Sort Lab

Sorting Beginner

Insertion Sort

Welcome to the Insertion Sort algorithm lab. Grow a sorted prefix by inserting each new value into its correct place. Use it when: Use for small or nearly sorted arrays. The time complexity is O(n^2), best O(n), and the space complexity is O(1). The pseudocode is: for i from 1 to n - 1 key = a[i] j = i - 1 while j >= 0 and a[j] > key a[j + 1] = a[j] j-- a[j + 1] = key As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(n^2), best O(n)

Space

O(1)

Pseudocode

for i from 1 to n - 1
  key = a[i]
  j = i - 1
  while j >= 0 and a[j] > key
    a[j + 1] = a[j]
    j--
  a[j + 1] = key
Open deeper structure lesson
1.0x