1 2 3 4 5 6归并排序法 7 8 9 归并排序是一种分治算法,其思想是将原始数组分割成较小的数组,直到每个小数组只有一个位置,接着将小数组归并成较大数组,知道最后只有一个排序完毕的大数组。10 11
1 var array=[32,12,45,2,57,1,35,7,9,23,32]; 2 3 function mergeRec(array){ 4 5 var length=array.length; 6 if(length==1) 7 return array; 8 var mid = Math.floor(length/2); 9 var left = array.slice(0,mid);10 var right = array.slice(mid,length);11 12 return mergeSort(mergeRec(left),mergeRec(right));13 }14 15 function mergeSort(left,right){16 var result=[];17 do18 {19 if(left[0]>right[0]){20 result.push(right.shift());21 }22 else{23 result.push(left.shift());24 }25 }26 while(left.length>0&& right.length>0);27 28 return result.concat(left).concat(right);29 30 }31 32 var abcd = mergeRec(array);33 console.log(abcd);