Last active
December 27, 2021 06:38
-
-
Save hoyangtsai/1279ca39ac7ba88ddd023cf0aca7fa47 to your computer and use it in GitHub Desktop.
Merge two sorted arrays #snippet #array
This file contains hidden or 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
const arr1 = [3, 5, 6, 10, 11, 20]; | |
const arr2 = [1, 2, 7, 8, 15, 19]; | |
mergeTwo(arr1, arr2); // [1, 2, 3, 5, 6, 7, 8, 10, 11, 15, 19, 20] | |
// First Approach | |
// O(n log n) time & O(n) space | |
function mergeTwo(arr1, arr2) { | |
let result = [...arr1, ...arr2]; | |
return result.sort((a,b) => a-b); | |
} | |
// Greedy Approach (with edge cases) | |
// O(n) time & O(n) space | |
function mergeTwo(arr1, arr2) { | |
let merged = []; | |
let index1 = 0; | |
let index2 = 0; | |
let current = 0; | |
while (current < (arr1.length + arr2.length)) { | |
let isArr1Depleted = index1 >= arr1.length; | |
let isArr2Depleted = index2 >= arr2.length; | |
if (!isArr1Depleted && (isArr2Depleted || (arr1[index1] < arr2[index2]))) { | |
merged[current] = arr1[index1]; | |
index1++; | |
} else { | |
merged[current] = arr2[index2]; | |
index2++; | |
} | |
current++; | |
} | |
return merged; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code from William Vincent blog, JavaScript: Merge Two Sorted Arrays