From 0e7675a48e75c0539816615dd8d428a6b14a6012 Mon Sep 17 00:00:00 2001 From: shellhub Date: Mon, 7 Oct 2019 16:28:27 +0800 Subject: [PATCH] mergeSortedArrayList --- .../Lists/MergeSortedArrayList.java | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 DataStructures/Lists/MergeSortedArrayList.java diff --git a/DataStructures/Lists/MergeSortedArrayList.java b/DataStructures/Lists/MergeSortedArrayList.java new file mode 100644 index 00000000..ea32e031 --- /dev/null +++ b/DataStructures/Lists/MergeSortedArrayList.java @@ -0,0 +1,60 @@ +package DataStructures.Lists; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author https://github.com/shellhub + */ + +public class MergeSortedArrayList { + public static void main(String[] args) { + List listA = new ArrayList<>(); + List listB = new ArrayList<>(); + List listC = new ArrayList<>(); + + /* init ListA and List B */ + for (int i = 1; i <= 10; i += 2) { + listA.add(i); /* listA: [1, 3, 5, 7, 9] */ + listB.add(i + 1); /* listB: [2, 4, 6, 8, 10] */ + } + + /* merge listA and listB to listC */ + merge(listA, listB, listC); + + System.out.println("listA: " + listA); + System.out.println("listB: " + listB); + System.out.println("listC: " + listC); + } + + /** + * merge two sorted ArrayList + * + * @param listA the first list to merge + * @param listB the second list to merge + * @param listC the result list after merging + */ + public static void merge(List listA, List listB, List listC) { + int pa = 0; /* the index of listA */ + int pb = 0; /* the index of listB */ + + while (pa < listA.size() && pb < listB.size()) { + if (listA.get(pa) <= listB.get(pb)) { + listC.add(listA.get(pa++)); + } else { + listC.add(listB.get(pb++)); + } + } + + /* copy left element of listA to listC */ + while (pa < listA.size()) { + listC.add(listA.get(pa++)); + } + + /* copy left element of listB to listC */ + while (pb < listB.size()) { + listC.add(listB.get(pb++)); + } + } + +}