Insertion Sort

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Insertion Sort

Approach

Build a sorted portion from left to right. For each new element, shift larger sorted elements one position right to make room, then insert the element at its correct position. This mimics how most people sort playing cards in their hand.

Complexity Analysis

Time
O(n²)
Space
O(1)

Pattern

Basic Sort

Why It Works

The sorted portion grows by one element each iteration. Shifting creates the correct gap. Best case O(n) for nearly sorted arrays since inner loop barely runs. Preferred over bubble sort for small or nearly sorted data.

Updated Feb 2026