Skip to content

Insertion sort JavaScript algorithm

  • by

The insertion sort algorithm in JavaScript is a simple sorting algorithm that works by building a sorted subarray one element at a time. It iterates over the array and compares each element with the sorted subarray on its left, inserting it in the correct position by shifting larger elements to the right. This process is repeated until the entire array is sorted.

Here’s a step-by-step explanation of the insertion sort algorithm in JavaScript:

  1. Start with an unsorted array of elements.
  2. Iterate over the array starting from the second element (index 1) to the end.
  3. For each element at the index i, store its value in a variable called currentValue.
  4. Initialize a variable j with the value of i - 1. This represents the index of the element to the left of currentValue.
  5. Compare currentValue with the element at the index j. If currentValue is smaller, move the element at the index j one position to the right (i.e., arr[j + 1] = arr[j]).
  6. Decrement j by 1 and repeat step 5 until j becomes less than 0 or the element at the index j is smaller than currentValue.
  7. Place currentValue in its correct sorted position, which is at the index j + 1 (i.e., arr[j + 1] = currentValue).
  8. Repeat steps 3-7 for each remaining element in the array.
  9. After the iteration is complete, the array will be sorted in ascending order.

Insertion sort JavaScript example

Simple example code implementation of the insertion sort algorithm in JavaScript.

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

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

    arr[j + 1] = currentValue;
  }

  return arr;
}

// Example usage:
const array = [5, 2, 4, 6, 1, 3];
const sortedArray = insertionSort(array);
console.log(sortedArray);

Output:

Insertion sort JavaScript algorithm

In this implementation, the insertionSort function takes an array arr as input and sorts it in ascending order using the insertion sort algorithm. It iterates through the array starting from the second element (i = 1). It compares each element with the sorted subarray on its left and inserts it in the correct position by shifting the larger elements to the right.

The sorted subarray grows with each iteration until the entire array is sorted. Finally, the sorted array is returned.

The algorithm has a time complexity of O(n^2) in the worst case but can perform well for small or partially sorted arrays.

Comment if you have any doubts or suggestions on this JS sorting algorithm topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *