Learn Simpli

Free Online Tutorial For Programmers, Contains a Solution For Question in Programming. Quizzes and Practice / Company / Test interview Questions.

Insertion Sort

How it works
  1. Insertion sorting algorithm starts iteration with choosing the one input element from the array,
  2. In every iteration, the insertion sorting algorithm moves the one element from the input array to the sorted array by finding its location where it shall be,
  3. It repeats until no input elements left in the input array
Performance
  1. Best case perfoarmace: Time complexity O(n),
  2. Averagecase performance: Time complexity O(n2),
  3. Worstcase performace: Time complexity O(n2),
Implement insertion sort
Lets implement the insertion sort in Javascript
/ insertion sort in javascript      
const insertionSort = (param) => {
    if (param) {
        let sizeOfArray = param.length;
        for (let i = 1; i < sizeOfArray; i++) {
            let inputElement = param[i];
            let j = i - 1;
            while (j >= 0 && param[j] > inputElement) {
                param[j + 1] = param[j];
                j = j - 1;
            }
            param[j + 1] = inputElement;
        }
        return param;
    }
};
let sortedArray = insertionSort([5, 3, 6, 7, 2, 1]);
console.log(sortedArray);
// output
// [1, 2, 3, 5, 6, 7]