SHARE
TWEET

Untitled

a guest May 19th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mergeSort = (A) => {
  2.   if (A.length <= 1) {
  3.     return A;
  4.   }
  5.  
  6.   const middle = Math.floor(A.length / 2);
  7.   const left = A.slice(0, middle);
  8.   const right = A.slice(middle);
  9.  
  10.   return merge(mergeSort(left), mergeSort(right));
  11. }
  12.  
  13. const merge = (left, right) => {
  14.   const sortedArray = [];
  15.   let indexLeft = 0;
  16.   let indexRight = 0;
  17.  
  18.   while (indexLeft < left.length && indexRight < right.length) {
  19.     if (left[indexLeft] < right[indexRight]) {
  20.       sortedArray.push(left[indexLeft]);
  21.       indexLeft++;
  22.     } else {
  23.       sortedArray.push(right[indexRight]);
  24.       indexRight++;
  25.     }
  26.   }
  27.  
  28.   return [...sortedArray, ...left.slice(indexLeft), ...right.slice(indexRight)]
  29. }
  30.  
  31. const list = [5, 9, 2, 3];
  32.  
  33. const sorted = mergeSort(list);
  34.  
  35. console.log('sorted --->', sorted);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top