Typorithm · easy

Insertion Sort

▷ Interactive algorithm labsortinginsertion-sortshiftingquadratic-time
Saved on this device
Full lesson · 35 learning steps Open any exercise for focused practice
1

Step 1 of 35 · intro card

Learn Insertion Sort

0%

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.

Preparing algorithm lab…
01

Start at index 1 because index 0 is already a sorted side of one item.

02

Store current before shifting values can overwrite its position.

03

Shift larger left-side values one slot to the right.

04

Insert current at j + 1, the open slot after the scan stops.

05

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Function declaration

Define a function that sorts the array by inserting each value into a sorted left side.

function insertionSort(arr)

2. Outer loop

Start at index 1 because a single first item is already sorted by itself.

for (let i = 1; i < arr.length; i++)

3. Current item

Store the value we are about to insert into the sorted left side.

const current = arr[i]

4. Left-side pointer

Start comparing from the item immediately to the left of current.

let j = i - 1

5. Shift condition

Keep shifting while there are left-side values greater than current.

while (j >= 0 && arr[j] > current)

6. Shift right

Move a larger value one position to the right to make room for current.

arr[j + 1] = arr[j]

7. Move left

Move left to keep searching for the insertion point.

j--

8. Insert current

Place current into the open position after all larger values shifted right.

arr[j + 1] = current

9. Return sorted array

Return the array after every item has been inserted into order.

return arr

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Insertion Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn