歸併排序 js demo

下半年記憶發表於2020-12-20

歸併排序

歸併排序是一種穩定的排序方法。和選擇排序一樣,歸併排序的效能不受輸入資料的影響, 因為始終都是O(nlogn)的時間複雜度。代價是需要額外的記憶體空間。
function sortDemo2() {
   var arr1:number[] = [55,23,12,5,1,35,98,122,41,3,9,66,20];

   var res = mergeSort(arr1);
   

   function mergeSort(arr:number[]):number[] {
      if(arr.length < 2) return arr;
      var mid:number = arr.length >> 1;
      var left:number[] = arr.slice(0,mid);
      var right:number[] = arr.slice(mid);
      return merge(mergeSort(left),mergeSort(right));
   }

   function merge(a:number[],b:number[]):number[] {
       var res:number[] = [];
       while (a.length > 0 && b.length > 0){
           if(a[0] > b[0]){
               res.push(b.shift() as number)
           }else {
               res.push(a.shift() as number)
           }
       }
       while(a.length > 0){
           res.push(a.shift() as number)
       }
       while(b.length > 0){
           res.push(b.shift() as number)
       }
       return res;
   }

}

相關文章