Using merge sort to recursive sort an array JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers. The function should sort the array using the merge sort algorithm.

Merge Sort

Merge Sort is made up of two parts or processes −

  • a recursive part that splits up a collection into single units,
  • and then an iterative part that combines them back together in the right order.

Example

const arr = [23, 4, 67, 32, 1, 7, 56, 5, 89];
const mergeSort = arr => {
   if (arr.length < 2){
      return arr;
   }
   const middle = Math.floor(arr.length / 2);
   const left = arr.slice(0, middle), right = arr.slice(middle, arr.length);
   return merge(mergeSort(left), mergeSort(right));
};
const merge = (left, right) => {
   const res = [];
   while (left.length && right.length) {
      if (left[0] <= right[0]){
         res.push(left.shift());
      }
      else{
         res.push(right.shift());
      };
   }
   while (left.length){
      res.push(left.shift());
   };
   while (right.length){
      res.push(right.shift());
   };
   return res;
};
console.log(mergeSort(arr));

Output

And the output in the console will be −

[
   1, 4, 5, 7, 23,
   32, 56, 67, 89
]
raja
Published on 25-Nov-2020 10:22:51
Advertisements