FlowLab Logo

Insertion Sort Visualizer

SlowFast
520
(7)
44
[0]
70
[1]
13
[2]
70
[3]
68
[4]
57
[5]
45
[6]
Current Element
Comparing
Moving
Sorted
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(n²) worst case, O(n) best case
Space Complexity: O(1) - in-place sorting
Stable: Yes - maintains relative order of equal elements
How it works: Build sorted portion one element at a time by inserting it into its correct position among previously sorted elements.
Best case: Already sorted array - only O(n) comparisons needed
Use case: Efficient for small datasets and nearly sorted arrays
Implementation
function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    let key = arr[i], j = i-1;
    while (j >= 0 && arr[j] > key) {
      arr[j+1] = arr[j];
      j--;
    }
    arr[j+1] = key;
  }
  return arr;
}