prep4place
Back to Visualizer

Insertion Sort

Insertion Sort builds the final sorted array one item at a time. It's efficient for small datasets and nearly sorted arrays, working like sorting playing cards in your hands.

Best: O(n)Avg: O(n²)Space: O(1)
Size:20
Speed:50%
Default
Comparing
Swapping
Sorted
Pivot
Current
0
Comparisons
0
Swaps

How It Works

  1. 1Start with the second element (first is already sorted)
  2. 2Compare current element with sorted portion
  3. 3Shift larger elements one position to the right
  4. 4Insert current element in its correct position
  5. 5Repeat for all remaining elements
  6. 6Like sorting playing cards in your hand

Time Complexity

Best CaseO(n)
Average CaseO(n²)
Worst CaseO(n²)
Space ComplexityO(1)

Code

function insertionSort(arr) {
  const n = arr.length;
  
  for (let i = 1; i < n; i++) {
    const key = arr[i];
    let j = i - 1;
    
    // Move elements greater than key
    // one position ahead
    while (j >= 0 && arr[j] > key) {
      arr[j + 1] = arr[j];
      j--;
    }
    
    arr[j + 1] = key;
  }
  
  return arr;
}