The Insertion Sort algorithm is a very interesting question that you may have heard in your school or college asked in many interviews including FAANG companies.


Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration.


Insertion sort works similarly as we sort cards in our hands in a card game. 

We assume that the first card is already sorted then, we select an unsorted card. If the unsorted card is greater than the card in hand, it is placed on the right otherwise, to the left. In the same way, other unsorted cards are taken and put in their right place.

A similar approach is used by insertion sort.


Insertion Sort Working:


1. The first element in the array is assumed to be sorted. Take the second element and store it separately in the key. 

Compare the key with the first element. If the first element is greater than the key, then the key is placed in front of the first element.


2. Now, the first two elements are sorted. 

Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array.


3. Similarly, place every unsorted element in its correct position.



Let's start with the algorithm,


var insertionSort = function(array){

    let i, key, j; 

    for (i = 1; i < array.length; i++)

    { 

        key = array[i]; 

        j = i - 1; 

   

        /* Move elements of arr[0..i-1], that are 

        greater than key, to one position ahead 

        of their current position */

        while (j >= 0 && array[j] > key)

        { 

            array[j + 1] = array[j]; 

            j = j - 1; 

        } 

        array[j + 1] = key; 

    } 

    return array;

}



Time Complexities:

  • Worst Case Complexity O(n2): Suppose, an array is in ascending order, and you want to sort it in descending order. In this case, worst-case complexity occurs. Each element has to be compared with each of the other elements so, for every nth element, (n-1) number of comparisons are made. Thus, the total number of comparisons = n*(n-1) ~ n2

  • Best Case Complexity O(n)When the array is already sorted, the outer loop runs for n number of times whereas the inner loop does not run at all. So, there is only n number of comparisons. Thus, complexity is linear.

  • Space Complexity O(n2):  Space complexity is O(1) because an extra variable is used for swapping. In the optimized bubble sort algorithm, two extra variables are used. Hence, the space complexity will be O(2).


I hope you understood the algorithm. If you have any doubts, please let us know in the comments.