mergeSort questions

Tell us what’s happening:
Describe your issue in detail here.

I’m having a hard time figuring out how to implement the mergeSort algorithm.
Following the challenge suggestions, I just got the merge function (for merging two sorted arrays) working, I think, but there are a couple of points about the mergeSort function that is unclear to me.

  1. Why split the initial array into halves?
    If we need single item arrays, why bother? Couldn’t we just iterate over the initial array and create an array for every element?
  2. Aren’t we trying to obtain something like: mergedArr = [[4], [22], [13], [2], [10] ] to feed our merge function?
    The only way I can think of for returning all the halves at once is creating an array of single item arrays. Is this correct?

As I don’t want to look at the solutions just yet I was hoping someone could push me in the right direction.

Thank you!

Challenge: Implement Merge Sort

Link to the challenge:

The reason this wouldn’t work is because you wouldn’t have the resulting call stack from calling mergeSort recursively.

merge expects two sorted arrays as arguments, and should return a sorted array comprised of the two passed to it.

merge([1,3,5],[2,4]) // should return [1,2,3,4,5]

After recursively subdividing the array passed to mergeSort, your call stack is all lined up to merge the sub-arrays into sorted arrays.

1 Like

Ok, thanks for your clarifications. I’ll see if I can come up with a working solution.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.