FAQ: Merge Sort: JavaScript - Merging

This community-built FAQ covers the “Merging” exercise from the lesson “Merge Sort: JavaScript”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Pass the Technical Interview with JavaScript

FAQs on the exercise Merging

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

while (leftArray.length > 0 && rightArray.length > 0)

" Because the while loop continues until either leftArray or rightArray is empty, …"

This contradicts itself. The while loop goes until BOTH are empty. I tried this without the concat because it seems like it should be useless if the condition is that BOTH left and right are empty. seems like it should be || (or).

What am I not understanding?

In this case the “and” operator && is doing exactly what you suggest it should. The code inside a while loop repeats as long as the condition evaluates to truthy. If either array has a length that isn’t greater than zero, the condition evaluates to falsy, and control is passed to whatever comes after the loop. Were you to change it to ||, then the loop would continue to iterate until both arrays are empty.

After finishing the exercise below and passing it, the output of the code was: [ 2, 3, 5, 4, 90, 7 ].
I thought the ‘90’ was suppose to be the last element in the list since it is the greatest number. So am I missing something or is there something else?

const mergeSort = (startArray) => {
const length = startArray.length;
if (length === 1) {
return startArray;
}

const mid = Math.floor(length / 2);
const leftArray = startArray.slice(0, mid);
const rightArray = startArray.slice(mid, length);

return merge(mergeSort(leftArray), mergeSort(rightArray))
}

const merge = (leftArray, rightArray) => {
const sortedArray = ;

while(leftArray.length > 0 && rightArray.length > 0){
if(leftArray[0] < rightArray[0]){
sortedArray.push(leftArray[0])
leftArray.shift()
}else{
sortedArray.push(rightArray[0])
rightArray.shift()
}

return sortedArray.concat(leftArray).concat(rightArray)

}
}

const inputArr = [3, 5, 2, 90, 4, 7];

console.log(mergeSort(inputArr));

module.exports = {
mergeSort
};

1 Like

Turns out I was supposed to ‘return’ outside the while loop. I’ll keep this here just incase someone has a brain wet fart like me.

const mergeSort = (startArray) => {
const length = startArray.length;
if (length === 1) {
return startArray;
}

const mid = Math.floor(length / 2);
const leftArray = startArray.slice(0, mid);
const rightArray = startArray.slice(mid, length);

return merge(mergeSort(leftArray), mergeSort(rightArray))

}

const merge = (leftArray, rightArray) => {
const sortedArray = ;

while (leftArray.length > 0 && rightArray.length > 0) {
    if (leftArray[0] < rightArray[0]) {
        sortedArray.push(leftArray[0])
        leftArray.shift()
    } else {
        sortedArray.push(rightArray[0])
        rightArray.shift()
    }
}
return sortedArray.concat(leftArray).concat(rightArray)

}

const inputArr = [3, 5, 2, 90, 4, 7];

console.log(mergeSort(inputArr));

2 Likes

I made the same mistake. Thanks for posting!

I guess you could do the merge using || instead of &&
so that you’d have
while (leftArray.length > 0 || rightArray.length > 0) {
but you’d have to do something to deal with the case of either of the lengths being 0,
so that all the elements of are added to sortedArray even if one of the arrays is empty.
If you’d do that, then you wouldn’t need the .concat at the end.

const merge = (leftArray, rightArray) => {
  const sortedArray = [];
  while (leftArray.length != 0 || rightArray.length != 0) {
    if (leftArray.length == 0) {
      sortedArray.push(rightArray.shift()); // .shift() removes element at [0] and returns it
    }
    else if (rightArray.length == 0 || leftArray[0] < rightArray[0]) {
      sortedArray.push(leftArray.shift()); // .shift() returns element at [0] after removing it
    }
    else {
      sortedArray.push(rightArray.shift()); // .shift() returns element at [0] after removing it
    }
  }
  return sortedArray;
}