Search code examples
javascriptarrayssortinginsertion-sort

How to implement insertion sort for two arrays in ES6


Let's say that I have two arrays:

arr1 - [90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16]

and

arr2 - [21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9]

I want to implement insertion sort for two arrays and receive the sorted result array:

[
  90, 86, 72, 64, 64, 64, 56, 44,
  24, 21, 20, 20, 19, 17, 16, 16,
  15, 15, 15, 13, 13,  9,  9,  9,
   7,  7
]

I know that I can achieve it indirectly with:

resultArray = arr1.concat(arr2).sort(function(a, b) {return b - a});

but it's not the best solution when it comes to performance.

I will be grateful for suggestions on how to achieve the above assumption with ES6 usage.


Solution

  • Use spread operator to concatenate, then arrow function to sort:

    let arr1 = [90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16];
    let arr2 = [21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9];
    
    let resultArray = [...arr1, ...arr2].sort((a, b) => b - a);
    
    console.log("arr1:");
    console.log("["+arr1.join(", ")+"]");
    console.log("arr2:");
    console.log("["+arr2.join(", ")+"]");
    console.log("resultArray:");
    console.log("["+resultArray.join(", ")+"]");
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Testing for larger Arrays:

    let arr1 = [90, 44, 64, 16, 24, 20, 64, 86, 20, 64, 56, 72, 16];
    let arr2 = [21, 13, 9, 13, 15, 7, 17, 15, 9, 19, 7, 15, 9];
    
    for(let i=0; i<10; i++) {
      arr1 = arr1.concat(arr1);
      arr2 = arr2.concat(arr2);
    };
    
    let start = null;
    let resultArray = null;
    
    start=new Date();
    resultArray = [...arr1, ...arr2].sort((a, b) => b - a);
    console.log("First resultArray took " + (Date.now() - start) + "ms");
    
    start = null;
    resultArray = null;
    start=new Date();
    resultArray = arr1.concat(arr2).sort(function(a, b) {return b - a});
    console.log("Second resultArray took " + (Date.now() - start) + "ms");
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    Seems like let resultArray = [...arr1, ...arr2].sort((a, b) => b - a); takes longer than what resultArray = arr1.concat(arr2).sort(function(a, b) {return b - a}); takes...