Merge Sort Algorithm in JavaScript

Sorting algorithms are very important to know and implement. Today, I want to go over one of the most popular sorting algorithms called merge sort implemented in JavaScript.
What is Merge Sort?
Merge sort is one of the most popular sorting algorithms today and it uses the concept of divide and conquer to sort a list of elements. Meaning, it will divide the bigger problem into smaller problems and then solve each of the small problems in order to solve the bigger problem that we started out with.
Implementation
Planning
Now that we talked briefly about merge sort, let’s get right into the implementation of the merge sort.
(Note: I will be implementing the merge sort in JavaScript using recursion to sort an unsorted array in an ascending order.)
Before we get straight into writing code, let’s first identify the problem, plan, and come up with a solution. Let’s take an example array [10, -1, 2, 5, 0, 6, 4, -5]. This is obviously an unsorted array. That is exactly our problem and we must sort this array using merge sort. Merge sort requires dividing the problem into smaller problems. So let’s look at a diagram of how this will look like:

Notice that at each level we divide the array into two halves until we get bunch of single element arrays. This is the divide portion of the divide and conquer method. Then, we start merging and sorting the smaller arrays in a series of steps which is the conquer portion of divide and conquer.
Code
We now have identified the problem and have a plan on how we want to go about implementing the merge sort. So let’s code!





