Insertion Sort Visualizer
Interactive visualization of insertion sort algorithm with step-by-step code execution
Array Visualization
Controls
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}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
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
Pick Next Element
Select the next unsorted element as key
Compare with Sorted
Compare key with elements in sorted portion
Shift Elements
Shift larger elements one position right
Insert Key
Place key at its correct position
Repeat Process
Continue until all elements are processed