Skip to content

Instantly share code, notes, and snippets.

@ncallaway
Last active December 3, 2022 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ncallaway/eee53d7a2dbd3d5ef1b53a2ccc8af33d to your computer and use it in GitHub Desktop.
Save ncallaway/eee53d7a2dbd3d5ef1b53a2ccc8af33d to your computer and use it in GitHub Desktop.
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