Today let’s take a look at Merge Sorting with JavaScript!
What is merge sort? It’s one of the quicker and more popular ways to sort a group numerically or alphabetically. Here we’re going to write a merge sort algorithm that will sort numerically two arrays.
It’s important to understand how merge sorting logic works. Essentially, we will continually divide the arrays into halves until we are finally left with single elements. Once the arrays are broken down, we then merge them back together, but in proper order over and over until we finally have the big array again. We will need two functions to execute this, one that sorts these arrays after splitting them, and one that merges them back together.
First, we want to write the merge function. This will act as a helper function for the mergeSort function, which will take in two arrays. We start by making an empty array, then using a while loop, we will push the elements into the empty array, using the shift method. Once this while loop is finished, we will return the new array, while concatenating any remaining elements of the two arrays. It looks something like this:
Once that is finished, we can move on to our mergeSort function. Here, the function will take in an unsorted array, and it is here that we will divide the array into two halves. Once this array is split, we will use our merge helper function and plug in the two halves, which will return a sorted array. It looks something like this:
Looks good! Altogether, we are left with this:
I hope this was helpful! Cheers.