Advertisement
Meruem

Merge Sort

May 8th, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var Mergesort = (function() {
  2.  
  3.  
  4.   function sort(array) {
  5.  
  6.     var length = array.length,
  7.         mid    = Math.floor(length * 0.5),
  8.         left   = array.slice(0, mid),
  9.         right  = array.slice(mid, length);
  10.  
  11.     if(length === 1) {
  12.       return array;
  13.     }
  14.  
  15.     return merge(sort(left), sort(right));
  16.  
  17.   }
  18.  
  19.  
  20.   function merge(left, right) {
  21.  
  22.     var result = [];
  23.  
  24.     while(left.length || right.length) {
  25.  
  26.       if(left.length && right.length) {
  27.  
  28.         if(left[0] < right[0]) {
  29.           result.push(left.shift());
  30.         } else {
  31.           result.push(right.shift());
  32.         }
  33.  
  34.       } else if (left.length) {
  35.         result.push(left.shift());
  36.       } else {
  37.         result.push(right.shift());
  38.       }
  39.  
  40.     }
  41.  
  42.     return result;
  43.  
  44.   }
  45.  
  46.   return {
  47.     sort: sort
  48.   };
  49.  
  50. })();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement