-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraylistMerge.java
More file actions
101 lines (77 loc) · 2.22 KB
/
Copy pathArraylistMerge.java
File metadata and controls
101 lines (77 loc) · 2.22 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class ArraylistMerge {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> listA = new ArrayList<Integer>();
ArrayList<Integer> listB = new ArrayList<Integer>();
ArrayList<Integer> listC = new ArrayList<Integer>();
listA.add(1);
listA.add(4);
listA.add(6);
listA.add(7);
listB.add(2);
listB.add(3);
listB.add(4);
listB.add(7);
listC.add(1);
listC.add(2);
listC.add(4);
listC.add(7);
listC.add(9);
ArrayList<ArrayList> lists = new ArrayList<ArrayList>();
lists.add(listA);
lists.add(listB);
lists.add(listC);
ArrayList<Integer> listIndex = new ArrayList<Integer>();
int numOfElements = 0;
for(int i = 0; i < lists.size();i++){
listIndex.add(0);
numOfElements += lists.get(i).size();
}
ArrayList<Integer> resultList = mergeLists(lists, listIndex, numOfElements);
System.out.println(resultList.toString());
}
/* Function takes in ArrayList of lists, List containing indexes to use, and total number of elements
Returns a mergedList
*/
private static ArrayList<Integer> mergeLists(List<ArrayList> lists, List<Integer> indices, int totalSize){
int currentMin = -1;
int currentValue;
int currentIndex;
int indexToUpdate = 0;
int currentCount;
int currentElement = 0;
ArrayList<Integer> resultList = new ArrayList<Integer>(totalSize);
ArrayList<Integer> currentList = new ArrayList<Integer>();
while (currentElement < totalSize) {
for(int i=0; i < lists.size(); i++)
{
currentList = lists.get(i);
currentIndex = indices.get(i);
if (currentIndex < currentList.size()) {
currentValue = currentList.get(currentIndex);
if (currentMin == -1) {
currentMin = currentValue;
indexToUpdate = i;
}
else if (currentValue < currentMin) {
currentMin = currentValue;
indexToUpdate = i;
}
}
}
resultList.add(currentMin);
currentCount = indices.get(indexToUpdate);
// currentCount++;
indices.set(indexToUpdate, ++currentCount);
currentElement++;
currentMin = -1;
}
return resultList;
}
}