Martin
Martin

Reputation: 1267

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.

Upvotes: 0

Views: 143

Answers (2)

iAmOren
iAmOren

Reputation: 2804

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...

Upvotes: 1

Aplet123
Aplet123

Reputation: 35512

You can sort the arrays separately then merge them:

const sarr1 = arr1.sort((a, b) => b - a);
const sarr2 = arr2.sort((a, b) => b - a);
const tot = [];
let arr1i = 0;
let arr2i = 0;
while (arr1i < sarr1.length && arr2i < sarr2.length) {
    if (sarr1[arr1i] >= sarr2[arr2i]) {
        tot.push(sarr1[arr1i]);
        arr1i++;
    } else {
        tot.push(sarr2[arr2i]);
        arr2i++;
    }
}
while (arr1i < sarr1.length) {
    tot.push(sarr1[arr1i ++]);
}
while (arr2i < sarr2.length) {
    tot.push(sarr2[arr2i ++]);
}
// tot now contains the fully sorted array

Upvotes: 1

Related Questions