Skip to content

mergeSortedArrayList #982

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 7, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions DataStructures/Lists/MergeSortedArrayList.java
Original file line number Diff line number Diff line change
@@ -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<Integer> listA = new ArrayList<>();
List<Integer> listB = new ArrayList<>();
List<Integer> 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<Integer> listA, List<Integer> listB, List<Integer> 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++));
}
}

}