Iterative MergeSort153 views

AlgoPill
 function iterativeMergeSort(list){
    function merge(lst,beg1,end1,beg2,end2,aux){
         var c = beg1, // counter for auxiliary array
             beg= beg1, // copy beg and end
             end = end2;
         while(beg1<=end1&&beg2<=end2){
             if(lst[beg1]<lst[beg2]){
                 aux[c++] = lst[beg1++];
             } else {
                 aux[c++] = lst[beg2++];
             }
         }
         // copy remaining items if any
         while(beg1<=end1){
             aux[c++] = lst[beg1++];
         }
         while(beg2<=end2){
             aux[c++] = lst[beg2++];
         }
         // now copy sorted elements from aux to actual list
         while(beg<=end){
            lst[beg]=aux[beg++];
         }
         return lst;
    }

    var i,m,
        r = []; // buffer required for merge routine
    for(m=1;m<=list.length;m=m*2){ // list sizes of 1,2,4,8,16 etc.
        for(i=0;i < list.length-m;i+=2*m){ // for each alternative list of size m
            //merge list [i...i+m-1] and [i+m....i+2*m-1]
            list = merge(list,i,i+m-1,i+m,Math.min(i+2*m-1,list.length-1),r);
        }
    }
    return list;
}

Problem Statement: Given a list of integers arrange them in ascending order.

Post a Comment

You must be logged in to post a comment.