Author -  Sai gowtham

How to implement Insertion sort algorithm in JavaScript

In this tutorial, we will learn about the insertion sort algorithm and its implementation in JavaScript.

Insertion sort maintains a sorted list and unsorted list in the same array. it finds the correct position to insert the item in the sorted list that’s why it’s called insertion sort.

In the below diagram, red color items are sorted and yellow ones are unsorted.

insertion sort algorithm example .

Let’s write an algorithm.

function insertionSort(array,length=array.length){
  return array
}

Next, we need to create a for loop which starts from 1. Inside the for loop we declared and initialized the temp variable with arr[i].

function insertionSort(array,length=array.length){
  for(var i = 1 ;  i < length ; i++){
    var temp = arr[ i ];
  }
  return array;
}

In nested for loop we are moving backward.Inside the nested for loop we need to swap the arr[j+1] = arr[j].

function insertionSort(array,length=array.length){
  for(var i = 1 ;  i < length ;i++){
    var temp = array[ i ];
    for(var j = i-1 ; j>-1 && array[ j ]>temp; j--){
       array[ j+1 ] = array[ j ];
    }
  }
  return array;
}

final step update the array[i+1] with temp value;

Completed algorithm

function insertionSort(array,length=array.length){
  for(var i = 1 ;  i < length ;i++){
    var temp = array[ i ];
    for(var j = i-1 ; j>-1 && array[ j ]>temp; j--){
       array[ j+1 ] = array[ j ];
    }
    array[ j+1] = temp;
  }
  return array;
}

console.log(insertionSort([4,1,3,7,2])) // [1, 2, 3, 4, 7]

Visualization

insertion sort algorithm visualization

Time complexity

  • Best case - O(n)
  • Average case - O(n2)
  • Worst case - O( n 2)

Space complexity - O(n)

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY