Workspace Insertion Sort
0d
DSA Problem Sheet

Insertion Sort

Sort the sequence by inserting each new item into the already ordered prefix.

EXECUTION LAB

Sort the sequence by inserting each new item into the already ordered prefix.

Input and constraints
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
a = values.copy()
i = 1
while (i < len(a)):
key = a[i]
j = (i - 1)
while ((j >= 0) and (a[j] > key)):
a[(j + 1)] = a[j]
j = (j - 1)
a[(j + 1)] = key
i = (i + 1)
return a

Visualizer

Step 1 of 9
06j
12i
24
31

Inspect the current state

Shift a larger item right to make room for 2.

Variable watch

i 1j 0key 2

Step explanation

Shift a larger item right to make room for 2.

comparisons 3reads 2writes 0swaps 0recursiveCalls 0
Educational simulation · O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary space

Worked explanation

Insert a new playing card into the ordered hand you already hold.

Guided solution

Save the incoming key before shifting larger entries right.

O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary auxiliary space

Examples

Worked example · {"values":[6,2,4,1],"target":0} ⇒ [1,2,4,6]

Edge case 1 · {"values":[],"target":0} ⇒ []

Edge case 2 · {"values":[2,2],"target":0} ⇒ [2,2]

Progressive hints

Hint 1Insert a new playing card into the ordered hand you already hold.
Hint 2Save the incoming key before shifting larger entries right.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Overwriting the key before saving it silently duplicates another card.

Interview follow-up

Why is insertion sort useful on nearly sorted input?