-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathMergeKSortedArrays.java
77 lines (70 loc) · 2.19 KB
/
MergeKSortedArrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package SummerTrainingGFG.Heap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
/**
* @author Vishal Singh
* 17-01-2021
*/
public class MergeKSortedArrays {
static class Triplet implements Comparable<Triplet> {
int value;
int j;
int i;
/**
* @param value - value of the element
* @param i - pos of value in all arrays
* @param j - pos of value in its own array
*/
Triplet(int value, int i, int j) {
this.value = value;
this.i = i;
this.j = j;
}
@Override
public String toString() {
return "Triplet{ " +
"value=" + value +
", j=" + j +
", i=" + i +
" }";
}
@Override
public int compareTo(Triplet triplet) {
return value - triplet.value;
}
}
public static void mergeKSortedArrays(ArrayList<List<Integer>> list, int size) {
PriorityQueue<Triplet> pq = new PriorityQueue<>();
/*
* intitally put first elements of all the array in Min Heap*/
for (int i = 0; i < list.size(); i++) {
pq.add( new Triplet(list.get(i).get(0),i,0));
}
List<Integer> ans = new ArrayList<>();
while (!pq.isEmpty()){
Triplet temp = pq.poll();
ans.add(temp.value);
int arrayPos = temp.i;
int valuePos = temp.j;
if (valuePos+1 < list.get(arrayPos).size()){
pq.add(
new Triplet(
list.get(arrayPos).get(valuePos+1),
arrayPos,
valuePos+1
)
);
}
}
System.out.println("Sorted Array : "+ ans);
}
public static void main(String[] args) {
ArrayList<List<Integer>> list = new ArrayList<>();
list.add(Arrays.asList(10, 20, 30));
list.add(Arrays.asList(5, 15));
list.add(Arrays.asList(1, 9, 11, 18));
mergeKSortedArrays(list, list.size());
}
}