This post shows how to implement Insertion Sort in JavaScript — a simple sorting algorithm that builds the sorted array one element at a time, similar to how you might sort playing cards in your hand.

Insertion sort in JavaScript:

Explanation:
Insertion sort treats the first element as a sorted subarray of size one, then repeatedly takes the next unsorted element and inserts it into its correct position within the already-sorted part, shifting larger elements to the right as needed. It's efficient for small or nearly-sorted datasets.


See Insertion Sort in Action

Drag the slider to scrub through every shift and insertion, or use Play to watch it run automatically.


JavaScript Program to Implement Insertion Sort

function insertionSort(arr) {
  for (let i = 1; i < arr.length; i++) {
    const current = arr[i];
    let j = i - 1;

    while (j >= 0 && arr[j] > current) {
      arr[j + 1] = arr[j];
      j--;
    }

    arr[j + 1] = current;
  }

  return arr;
}

const numbers = [12, 11, 13, 5, 6];
console.log("Sorted array:", insertionSort(numbers));

Output:

Sorted array: [ 5, 6, 11, 12, 13 ]

Insertion sort is fast on nearly-sorted data and is actually used internally by some JavaScript engines for small arrays. See how it compares to Quick Sort for larger datasets, or practice it in our Code Runner.


Frequently Asked Questions About Insertion Sort in JavaScript

What is the time complexity of insertion sort?

Insertion sort runs in O(n²) time in the average and worst case, but only O(n) in the best case when the array is already sorted, since the inner while loop barely runs.

When is insertion sort a good choice?

It performs well on small arrays or data that's already mostly sorted, which is why some sorting library implementations switch to insertion sort for small subarrays as an optimization within algorithms like quick sort.

Is insertion sort a stable sorting algorithm?

Yes. Insertion sort only shifts elements that are strictly greater than the current element, so equal elements keep their original relative order.