Insertion Sort Visualizer

Interactive visualization of insertion sort algorithm with step-by-step code execution

Array Visualization

64
[0]
34
[1]
25
[2]
12
[3]
22
[4]
11
[5]
90
[6]
Current Index: 1 | Key Value: 0 | Position: 1
Comparisons: 0 | Shifts: 0
Key Element
Comparing
Shifting
Sorted Part
Sorted
Inserting

Controls

SlowFast

Insertion Sort Algorithm

1function insertionSort(array) {
2  const n = array.length;
3  
4  // Start from second element
5  for (let i = 1; i < n; i++) {
6    // Current element to be inserted
7    let key = array[i];
8    let j = i - 1;
9    
10    // Shift elements to the right
11    while (j >= 0 && array[j] > key) {
12      array[j + 1] = array[j];
13      j--;
14    }
15    
16    // Insert the key at correct position
17    array[j + 1] = key;
18  }
19  
20  return array;
21}
Step 1 of 6

Get the length of the array

About Insertion Sort

Understanding the fundamentals, properties, and complexity analysis of the insertion sort algorithm

What is Insertion Sort?

Insertion Sort builds the sorted array one element at a time by taking each element from the unsorted portion and inserting it into its correct position in the sorted portion. It's similar to how you would sort playing cards in your hand - picking up cards one by one and placing them in their proper position.

Advantages

  • Efficient for small datasets
  • Adaptive - O(n) for nearly sorted arrays
  • Stable sorting algorithm
  • In-place and online algorithm

Disadvantages

  • Poor performance for large datasets
  • O(n²) worst-case time complexity
  • More writes compared to selection sort

Properties

Type:Comparison
Stability:Stable
Best Case:O(n)
Average Case:O(n²)
Worst Case:O(n²)
Space:O(1)

When to Use

Small Arrays

Excellent for datasets with < 50 elements

Nearly Sorted Data

Optimal O(n) performance for sorted arrays

Online Algorithm

Can sort data as it arrives

Stable Sorting

When preserving relative order is important

Hybrid Algorithms

Used in Timsort and Introsort for small subarrays

Algorithm Steps

1

Pick Next Element

Select the next unsorted element as key

2

Compare with Sorted

Compare key with elements in sorted portion

3

Shift Elements

Shift larger elements one position right

4

Insert Key

Place key at its correct position

5

Repeat Process

Continue until all elements are processed