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:
To understand merge sort, you have to remember the few following things:
Here are the steps to follow:
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.
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