To describe merge sort, let’s just an analogy.

Assume you have a piece of lego that you can break apart. Each sub piece has its own numbers and you keep breaking and breaking until there is one piece each other, with their own numbers.

Here is a diagram to demonstrate how it will looks like:

Image for post

To understand merge sort, you have to remember the few following things:

  • Mergesort
  • merge

Here are the steps to follow:

  • Step 1: Create a function called mergeSort.
  • Step 2: Within mergeSort, create left and right subarray, take the first half of the elements, and copy it into the left subarray. Copy the second half of the elements into the right subarray.
  • Step 3: Call Merge sort recursively with left subarray(function itself)
  • Step 4: Call Merge sort recursively with right subarray(function itself)
  • Step 5: call merge with left subarray, right subarray, the original array itself, with size of the left array, and the size of the right array.

Within the Merge function, you will be comparing elements in the left and right subarray, with i and j as indices for tracking current element to be compared at each array respectively.

i and j starts at 0. You also have another indice,k, which is used to track the most current index which we are moving new elements in. If current left_arr[i] < right_arr[j], move left_arr[i] to arr[k] and increment i and k, else move right_arr[j] to arr[k], and increment j and k.

Here is the code for the mergeSort:

Over here, if there are less than 2 elements then we don’t even need to sort. We put half of the elements into left_arr, another half into right_arr. Then we call mergeSort and divide further into each subarray. Merge is the part that actually sorts things together.

#merge-sort #sorting-algorithms #web-development #algorithms #javascript

How to implement Merge Sort in javascript
1.30 GEEK