Learn-dsa..in 30 days!



























CC-18 : Merge K sorted arrays.

Description:

Given k sorted array of integers, merge the same. Sort order should be maintained in the merged array.

Test cases and expected outputs:

Input Parameters Expected outputs
The Arrays :
11,32,93,
4,56,90,
5,51,94,
Merged & Sorted:
4,5,11,32,51,56,90,93,94

Pseudocode:

Class IntInfo:

Create an internal class IntInfo.
We will extract integers from input arrays and for each individual integer, the instances of IntInfo will hold reference to one integer and its row Index and column index with respect to input array of arrays.

Class SortNums:

This class implements Comparator.compare() method. The method takes 2 instance of IntInfo and helps to sort the same by magnitude of the integers.

Method sortKArrays(str):

This method takes k integer arrays named nums as parameter.
Initialize a PriorityQueue instance named minHeap. Provide an instance of SortNums to the constructor the PriorityQueue to sort by magnitude of the integers.
Iterate through rows (only) of input k arrays:
Create an instance of IntInfo and name it firstInt.
Set firstInt.iIdx to idx.
Set firstInt.jIdx to 0.
Set firstInt.num to nums[iIdx][jIDx].
Add firstInt to minheap.
Initialize a ArrayList instance named sorted to collate the sorted integers.
While heapsize is not 0:
Remove a IntInfo instance named minNum from top of heap.
Add minNum.Num to the heap.
Set i=minNum.iIdx.
Set j=minNum.jIdx.
if (j< nums[i].length-1):
Create an instance of IntInfo and name it nextInt.
Set nextInt.iIdx to i.
Set nextInt.jIdx to j+1.
Set nextInt.num to nums[i][j+1].
Add nextInt to minheap.
Return sorted.

Code:

public class HeapSortKArrays {

class IntInfo{
	int iIdx;
	int jIdx;
	int num;
}

class SortNums implements Comparator<IntInfo> {
	public int compare(IntInfo num1, IntInfo num2) {
		if (num1.num < num2.num) {return -1;}
		if (num1.num > num2.num) {return 1;}
		return 0;
	}	
}
 
public ArrayList<Integer> sortKArrays(int[][] nums) {
	
	ArrayList<Integer> sorted=new ArrayList<Integer>();
	PriorityQueue<IntInfo> minHeap=new PriorityQueue<IntInfo>(new SortNums());
	for (int idx=0; idx < nums.length; idx++) {
		IntInfo firstInt=new IntInfo();
		firstInt.iIdx=idx;
		firstInt.jIdx=0;
		firstInt.num=nums[idx][0];
		minHeap.add(firstInt);
	}
	while (minHeap.size() !=0) {
		IntInfo minNum=minHeap.remove();
		sorted.add(minNum.num);
		int i=minNum.iIdx;
		int j=minNum.jIdx;
		if (j < nums[i].length-1) {
			IntInfo nextInt=new IntInfo();
			nextInt.iIdx=i;
			nextInt.jIdx=j+1;
			nextInt.num=nums[i][j+1];
			minHeap.add(nextInt);
			
		}
	}
	return sorted;
}
}

Click here to download and run code and test cases !