Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package week8;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Collections;
- public class homework_P6_28 {
- /*6.28 Write a method
- public static ArrayList<Integer> mergeSorted(ArrayList<Integer> a,
- ArrayList<Integer> b)
- that merges two sorted array lists, producing a new sorted array list. Keep an index
- into each array list, indicating how much of it has been processed already. Each time,
- append the smallest unprocessed element from either array list, then advance the
- index. For example, if a is
- 1 4 9 16
- and b is
- 4 7 9 9 11
- then mergeSorted returns the array list
- 1 4 4 7 9 9 9 11 16*/
- public static void main(String[] args) {
- ArrayList<Integer> firstList = newList(4, 99);
- ArrayList<Integer> secondList = newList(5, 99);
- ArrayList<Integer> mergeList = mergeSorted(firstList, secondList);
- printArray(firstList, "First List");
- printArray(secondList, "Second List");
- printArray(mergeList, "Merge Sorted List");
- }
- public static ArrayList<Integer> mergeSorted(ArrayList<Integer> a,
- ArrayList<Integer> b) {
- ArrayList<Integer> tempList = newList(a.size() + b.size(), 1);
- int pos1 = 0;
- int pos2 = 1;
- if (a.size() < b.size() || a.size() == b.size()) {
- for (int i = 0; i < a.size(); i++) {
- tempList.set(pos1, a.get(i));
- pos1 += 2;
- }
- for (int i = 0; i < b.size(); i++) {
- if (pos2 < pos1) {
- tempList.set(pos2, b.get(i));
- pos2 += 2;
- } else {
- tempList.set(pos2 - 1, b.get(i));
- pos2++;
- }
- }
- } else {
- for (int i = 0; i < b.size(); i++) {
- tempList.set(pos2, b.get(i));
- pos2 += 2;
- }
- for (int i = 0; i < a.size(); i++) {
- if (pos1 < pos2) {
- tempList.set(pos1, a.get(i));
- pos1 += 2;
- } else {
- tempList.set(pos1 - 1, a.get(i));
- pos1++;
- }
- }
- }
- Collections.sort(tempList);
- return tempList;
- }
- public static ArrayList<Integer> newList(int size, int rand) {
- ArrayList<Integer> temp = new ArrayList<Integer>();
- for (int i = 0; i < size; i++) {
- if (rand == 0) {
- temp.add(i + 1);
- } else {
- temp.add((int) (Math.random() * rand));
- }
- }
- return temp;
- }
- public static void printArray(ArrayList<Integer> arr, String abc) {
- String name = abc;
- System.out.printf("%12s: {", name);
- for (int i = 0; i < arr.size(); i++) {
- System.out.printf("%2d", arr.get(i));
- if (i < arr.size() - 1) {
- System.out.print(",");
- }
- }
- System.out.print("}; \n");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement