Merge sort in Java Merge all sequences

Write a program that reads several descending sorted sequences of ints and merges them into one sequence. The merged sequence should be also sorted in the same order. Note, a sequence can have identical elements.

Input data format

The first line contains the integer number of sequences NN.

The followed NN lines have two parts: the number of elements M_kM**k in a k-sequence and its elements.

Output data format

All elements of the merged sequence. The elements should be separated by spaces.

Constraints

1 \le N \le 100, 1 \le M_k \le 50000.1≤N≤100,1≤M**k≤50000.

Sample Input 1:

4
4 8 7 6 6
5 9 7 7 4 4
3 2 2 1
4 15 7 4 2

Sample Output 1:

15 9 8 7 7 7 7 6 6 4 4 4 2 2 2 1
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        final int numberOfArrays = scanner.nextInt();

        int[] temp = new int[0];
        for (int i = 0; i < numberOfArrays; i++) {
            final int arraySize = scanner.nextInt();

            final int[] array = new int[arraySize];
            for (int j = 0; j < array.length; j++) {
                array[j] = scanner.nextInt();
            }

            temp = merge(temp, array);
        }

        for (int elem : temp) {
            System.out.print(elem + " ");
        }
    }

    public static int[] merge(int[] a1, int[] a2) {
        int[] c = new int[a1.length + a2.length];
        int i = 0, j = 0, k = 0;

        while ((i < a1.length) && (j < a2.length)) {
            if (a1[i] >= a2[j]) {
                c[k] = a1[i];
                i++;
            } else {
                c[k] = a2[j];
                j++;
            }
            k++;
        }

        for (; i < a1.length; i++) {
            c[k] = a1[i];
            k++;
        }

        for (; j < a2.length; j++) {
            c[k] = a2[j];
            k++;
        }

        return c;
    }
}

posted @ 2020-08-17 08:04  longlong6296  阅读(214)  评论(0)    收藏  举报