#K53862. Merge Sorted Arrays
Merge Sorted Arrays
Merge Sorted Arrays
You are given two sorted arrays. Your task is to merge these arrays into one sorted array without using any built‐in sort functions.
The process is similar to the merge operation in the Merge Sort algorithm. Given two arrays, you are required to iterate through them simultaneously and build a new resulting array which has all of the elements in sorted order.
Formally, given two sorted arrays \(A\) and \(B\), produce an array \(C\) such that
[ C = A \cup B \quad \text{and} \quad \forall x, y \in C, \text{ if } x \text{ appears before } y, \text{ then } x \le y. ]
Your solution should read input from standard input and output the merged array to standard output.
inputFormat
The input is given via standard input (stdin) and has the following format:
n m a1 a2 ... an b1 b2 ... bm
Here, n
and m
are non-negative integers representing the sizes of the two sorted arrays. The second line contains n
integers (sorted in non-decreasing order) and the third line contains m
integers (also sorted in non-decreasing order). If n
or m
is 0, the corresponding line may be empty.
outputFormat
The output should be printed to standard output (stdout) as a single line containing the elements of the merged sorted array, separated by a single space. If the merged array is empty, output nothing.
## sample4 4
1 3 5 7
2 4 6 8
1 2 3 4 5 6 7 8