javascript的归并排序

function merge(left,right){
  var re=[];
  while(left.length>0 && right.length>0)
  {
    if(left[0]<right[0]){
    re.push(left.shift());
  }
  else{
    re.push(right.shift());
  }
}

  return re.concat(left).concat(right);
}

function mergeSort(array){
  if(array.length==1) return array;
  var mid=Math.floor(array.length/2);
  var left=array.slice(0,mid);
  var right=array.slice(mid);

  return merge(mergeSort(left),mergeSort(right));
}

var array=[234,123,1,23,123,2,11];
console.log(mergeSort(array));

/*
 mergeSort([234,123,1,23,123,2,11])
 |
 V
 merge(
   mergeSort([234,123,1]),
   mergeSort([23,123,2,11])
 );
 |
 V
 merge(
   merge(
     mergeSort([234]),
     mergeSort([123,1])
   ),
   merge(
     mergeSort([23,123]),
     mergeSort([2,11])
   )
 );
 |
 V
 merge(
   merge(
     mergeSort([234]),//arr=[234],
     merge([123],[1]);//arr=[1,123]
   ),//arr=[1],left=[234],right=[123] => arr=[1,123,234]
   merge(
     merge([23],[123]),//arr=[23,123]
     merge([2],[11])//arr=[2,11]
   )//arr=[2],left=[23,123],right=[11]
    //arr[2,11],left=[23,123],right=[] 
    //arr=[2,11,23,123]
 );
 |
 V
 merge([1,123,234],[2,11,23,123]);
 |
 V
 arr=[1],left=[123,234],right=[2,11,23,123]
 |
 V
 arr=[1,2],left=[123,234],right=[11,23,123]
 |
 V
 arr=[1,2,11],left=[123,234],right=[23,123]
 |
 V
 arr=[1,2,11,23],left=[123,234],right=[123]
 |
 V
 arr=[1,2,11,23,123],left=[123,234],right=[]
 |
 V
 arr=[1,2,11,23,123,123,234]
 */
张贴在js