Implementing insertion sort to sort array of numbers in increasing order using JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

Our function should make use of the insertion sort algorithm to sort this array of numbers in increasing order.

For example, if the input to the function is

Input

const arr = [5, 8, 1, 3, 9, 4, 2, 7, 6];

Output

const output = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Example

Following is the code −

 Live Demo

const arr = [5, 8, 1, 3, 9, 4, 2, 7, 6];
const insertionSort = (arr = []) => {
   let n = arr.length;
   for (let i = 1; i < n; i++) {
      let curr = arr[i];
      let j = i-1;
      while ((j > -1) && (curr < arr[j])) {
         arr[j+1] = arr[j];
         j--;
      }
      arr[j+1] = curr;
   };
   return arr;
}
console.log(insertionSort(arr));

Output

[1, 2, 3, 4, 5, 6, 7, 8, 9]
raja
Published on 24-Apr-2021 14:05:25
Advertisements