Skip to content

Commit 0e7675a

Browse files
mergeSortedArrayList
1 parent ea7c4ec commit 0e7675a

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package DataStructures.Lists;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* @author https://github.com/shellhub
8+
*/
9+
10+
public class MergeSortedArrayList {
11+
public static void main(String[] args) {
12+
List<Integer> listA = new ArrayList<>();
13+
List<Integer> listB = new ArrayList<>();
14+
List<Integer> listC = new ArrayList<>();
15+
16+
/* init ListA and List B */
17+
for (int i = 1; i <= 10; i += 2) {
18+
listA.add(i); /* listA: [1, 3, 5, 7, 9] */
19+
listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */
20+
}
21+
22+
/* merge listA and listB to listC */
23+
merge(listA, listB, listC);
24+
25+
System.out.println("listA: " + listA);
26+
System.out.println("listB: " + listB);
27+
System.out.println("listC: " + listC);
28+
}
29+
30+
/**
31+
* merge two sorted ArrayList
32+
*
33+
* @param listA the first list to merge
34+
* @param listB the second list to merge
35+
* @param listC the result list after merging
36+
*/
37+
public static void merge(List<Integer> listA, List<Integer> listB, List<Integer> listC) {
38+
int pa = 0; /* the index of listA */
39+
int pb = 0; /* the index of listB */
40+
41+
while (pa < listA.size() && pb < listB.size()) {
42+
if (listA.get(pa) <= listB.get(pb)) {
43+
listC.add(listA.get(pa++));
44+
} else {
45+
listC.add(listB.get(pb++));
46+
}
47+
}
48+
49+
/* copy left element of listA to listC */
50+
while (pa < listA.size()) {
51+
listC.add(listA.get(pa++));
52+
}
53+
54+
/* copy left element of listB to listC */
55+
while (pb < listB.size()) {
56+
listC.add(listB.get(pb++));
57+
}
58+
}
59+
60+
}

0 commit comments

Comments
 (0)