1. Function declaration
Define a function that sorts the array by inserting each value into a sorted left side.
function insertionSort(arr)Typorithm · easy
Step 1 of 35 · intro card
Sorting Algorithms
Insertion Sort builds a sorted left side one item at a time.
The left side of the array is treated as sorted. Each pass picks the next value as the current key.
The algorithm compares current with values on the left. Larger values shift one position right.
When shifting stops, current is inserted into the open slot. This makes the sorted left side grow by one.
Insertion Sort is especially useful for nearly sorted data, and it teaches while loops, shifting, and insertion points.
Start at index 1 because index 0 is already a sorted side of one item.
Store current before shifting values can overwrite its position.
Shift larger left-side values one slot to the right.
Insert current at j + 1, the open slot after the scan stops.
Best case is O(n) when the array is already sorted or nearly sorted.
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const current = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
return arr;
}Connect each part of the code to the concept before you type.
Define a function that sorts the array by inserting each value into a sorted left side.
function insertionSort(arr)Start at index 1 because a single first item is already sorted by itself.
for (let i = 1; i < arr.length; i++)Store the value we are about to insert into the sorted left side.
const current = arr[i]Start comparing from the item immediately to the left of current.
let j = i - 1Keep shifting while there are left-side values greater than current.
while (j >= 0 && arr[j] > current)Move a larger value one position to the right to make room for current.
arr[j + 1] = arr[j]Move left to keep searching for the insertion point.
j--Place current into the open position after all larger values shifted right.
arr[j + 1] = currentReturn the array after every item has been inserted into order.
return arrRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
Input[5,1,4,2,8]
One temporary value and a fixed number of indices. In-place does not mean zero extra memory. The input array is not counted as extra space.
One reusable value slot. Empty until the next operation needs it.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state