0

I must implement the nMerge, so I need to merge the arrays divided into N sub-arrays. This is the nMergeSort:

void nMergeSort(int arr[],int n, int low, int high){

    int *L,i,a;

    if(low < high){     

        L=SPLIT(k,low,high);        
        for(i=0;i<=n;i++){

            nMergeSort(arr,n,L[i],L[i+1]-1);            
        }

        nMerge(arr[],L[],n,low,high);       
    }

}

SPLIT is a function that create an array with the positions of the first elements of the N subarrays(at least I think so). How do I implement the nMerge method? I'm just stuck and I can not go on.

SaeX
  • 17,240
  • 16
  • 77
  • 97

1 Answers1

0

A simple implementation of an n-way merge is to do n-1 comparisons of the first elements of the n sorted groups, to find the smallest element / group, and then output that element and get the next element from that same group. One alternative is to create and update a minimum heap of some type to keep track of which group contains the current smallest element.

During an n-way merge, when the end of one of the groups is reached, it becomes an (n-1)-way merge, then (n-2)-way merge, and so on. When there's only one group remaining, it's copied, and the n-way merge for that set of groups is complete.

To implement nMerge, a variable for number of groups is maintained. For each group, it's common to have a current index or pointer, and an ending index or pointer or a down counter for the number of elements remaining in a group. These can be in separate arrays or in array of structures. The array(s) are reordered according to the current elements of the group, so that array[0] contains group information for the group with the smallest current element. When a group reaches it's end, then array[0] is swapped with array[number of groups - 1], and number of groups is decremented. When number of groups is reduced to 1 the remainder of the final group is copied.

rcgldr
  • 27,407
  • 3
  • 36
  • 61
  • @dariob - I don't have a standard example, but I updated my answer with more detail. – rcgldr Feb 01 '16 at 04:23
  • ok man, i think i'm more stuck than b4, now i have problems with the SPLIT. I think i had implemented the nMerge with an additional array that contains the counts of the subarrays, but no ideas how to do the SPLIT. Can you help? – dario b Feb 02 '16 at 09:42
  • @dariob - it might be easier to convert the counts into starting indices, so that L[0] = 0, L[1] = end of group 0, start of group 1, L[2] = end of group 1, start of group 2, ... L[n] = end of group n (== size of array). – rcgldr Feb 02 '16 at 23:23