Created
December 3, 2022 16:22
-
-
Save ncallaway/d4985343adce8b7b2309a82959c465fb to your computer and use it in GitHub Desktop.
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
function mergeSortedLists(list1: number[], list2: number[]): number[] { | |
// create a new, empty list to store the merged and sorted result | |
const mergedList: number[] = []; | |
// create two pointers to keep track of the current index in each list | |
let pointer1 = 0; | |
let pointer2 = 0; | |
// loop until one of the pointers reaches the end of its list | |
while (pointer1 < list1.length && pointer2 < list2.length) { | |
// compare the elements at the current pointers in each list | |
if (list1[pointer1] <= list2[pointer2]) { | |
// if the element in list1 is smaller or equal, add it to the merged list | |
// and move the pointer in list1 forward | |
mergedList.push(list1[pointer1]); | |
pointer1++; | |
} else { | |
// otherwise, add the element from list2 to the merged list and move the | |
// pointer in list2 forward | |
mergedList.push(list2[pointer2]); | |
pointer2++; | |
} | |
} | |
// once one of the pointers has reached the end of its list, we can add the | |
// remaining elements from the other list to the merged list | |
while (pointer1 < list1.length) { | |
mergedList.push(list1[pointer1]); | |
pointer1++; | |
} | |
while (pointer2 < list2.length) { | |
mergedList.push(list2[pointer2]); | |
pointer2++; | |
} | |
// return the merged and sorted list | |
return mergedList; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment