Created
November 17, 2022 19:09
-
-
Save marcusmotill/fa760aea25cbba028f8b6a4745156ea8 to your computer and use it in GitHub Desktop.
sort two arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// input is two ascending sorted arrays | |
// output is the product of the two arrays sorted ascending | |
// inputs | |
const input1 = [1, 2, 3, 4, 99]; | |
const input2 = [8, 10, 99, 101, 102]; | |
// define variables needed in loop | |
let output = []; | |
let pointer1 = 0; | |
let pointer2 = 0; | |
// eslint-disable-next-line no-constant-condition | |
while (true) { | |
/** | |
* if either pointer has reached the end of their respective input | |
* then we can take the remaining items in the other list and append it | |
* to our output | |
*/ | |
if (pointer1 + 1 > input1.length) { | |
output = [...output, ...input2.slice(pointer2)]; | |
break; | |
} else if (pointer2 + 1 > input2.length) { | |
output = [...output, ...input1.slice(pointer1)]; | |
break; | |
} | |
const value1 = input1[pointer1]; | |
const value2 = input2[pointer2]; | |
/** | |
* find the smaller of the two pointer values and push to output | |
* increment the respective pointer | |
*/ | |
if (value1 < value2) { | |
output.push(value1); | |
pointer1 += 1; | |
} else if (value1 > value2) { | |
output.push(value2); | |
pointer2 += 1; | |
} else { | |
// we want both values in the output array if they are equal | |
output.push(value1); | |
output.push(value2); | |
pointer1 += 1; | |
pointer2 += 1; | |
} | |
} | |
// [ 1, 2, 3, 4, 8, 10, 99, 99, 101, 102 ] | |
console.log(output); | |
return output; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment