Merge sort is one of the efficient sorting algorithm that applies the principle or uses divide and conquer pattern.

Merge sort divides a given unsorted array into two equal halves sub arrays until the nth (last) array contains a single element. This is based on the fact that array of a single element is always sorted.

Merging of Sorted Arrays

The sub arrays are merged by comparison of the elements of the first array to the second, starting from the first element of both arrays. When compared, the one lesser than is pushed to a single sub array. This action is continued until all the sub arrays are sorted and merged.

merge sort algorithm

merge sort visualization

We are going to use two functions to implement this algorithm viz: mergeSort function and merge function. MergeSort function will recursively divide the unsorted array into nth sub arrays as aforementioned while the merge function will act as the name implies, merging the sub arrays.

#javascript #merge-sort #data-structures #algorithms

Implement Merge Sort Algorithm in JavaScript.
2.35 GEEK