0

I want to write an algorithm of time O(n*lgk) for the merge of k sorted arrays into one sorted array, where n is the total number of elements of all the input arrays.

Could you give me a hint how we could do this?

EDIT: I wrote the following algorithm:

Algorithm(L) // L=[L1, L2, L3, ...., Lk]
  list=LNEW;
  for (i=1; i<=k; i++){
      H[i]=L[i][1];
  }
  BUILD-HEAP(H);
  j=1;
  while (j<n){
         LNEW[j]=H[1];
         yes=0;
         m=1;
         while (m<=k and L[m][j]!=NULL and L[m][j+1]!=NULL and yes!=1){
                if (H[1]==L[m][j]){
                    H[1]=L[m][j+1];
                    yes=1;
                    Heapify(H);
                }
                j=j+1;
  }

Could you tell me if it is right?

Mary Star
  • 359
  • 5
  • 23
  • 1
    Make a [heap](http://en.wikipedia.org/wiki/Heap_(data_structure)) of the `k` head elements, then remove the lowest and insert one from the array it originated from. Repeat until all inputs are empty. – Mark Ransom Jan 19 '15 at 21:35
  • Could I just write the steps that are required to be done or should I write a pseudocode? – Mary Star Mar 29 '15 at 22:42

1 Answers1

0

We can maintain an array of k elements firstFree, where firstFree[i] is the first unused element in the i-th array. Additionaly, we can have a heap that contains at most k elements(each element is a pair (value, an index of the array that contains this value)). Initially we should put the first elements of all given arrays into this heap. After that, we should repeat the following process until the heap is empty:

  1. Pop the top element of the heap. Add it to the output array.

  2. Increment the firstFree value for the array which contains this element. If it does not exceed this array's size, add the next element to the heap.

This algorithm does n insert and pop operations, so its time complexity is O(n log k).

kraskevich
  • 17,514
  • 3
  • 26
  • 42
  • So would it be enough to write the steps or would I have to write an algorithm? – Mary Star Mar 29 '15 at 22:40
  • The number of insert and pop operations are in the order of n*k. so complexity of this approach is O(nk log k). https://www.geeksforgeeks.org/merge-k-sorted-arrays/ – Saikat Das Feb 07 '18 at 10:30