#K39567. Merge and Sort Two Lists

    ID: 26449 Type: Default 1000ms 256MiB

Merge and Sort Two Lists

Merge and Sort Two Lists

You are given two sorted lists of integers. Your task is to merge these two lists into a single sorted list. The lists are individually sorted in non-decreasing order.

The merging must be performed in the lexicographically smallest way by sequentially comparing the front elements of both lists. Formally, if we denote the two lists as \(a\) and \(b\), then the merged list \(c\) is constructed using the following procedure:

\(\text{Initialize } i = 0, j = 0.\)

\(\textbf{While } i < n \text{ and } j < m\):

  • If \(a[i] \leq b[j]\), append \(a[i]\) to \(c\) and increment \(i\).
  • Otherwise, append \(b[j]\) to \(c\) and increment \(j\).

Finally, append any remaining elements from list \(a\) or \(b\) to \(c\). This guarantees that the resulting merged list is sorted in non-decreasing order.

See the sample examples for clarity.

inputFormat

The input is read from stdin and consists of three lines:

  1. The first line contains two integers \(n\) and \(m\) separated by a space, representing the number of elements in the first and second list respectively.
  2. The second line contains \(n\) space-separated integers in non-decreasing order.
  3. The third line contains \(m\) space-separated integers in non-decreasing order.

outputFormat

Output the merged and sorted list to stdout as a single line of space-separated integers.

## sample
3 3
1 3 5
2 4 6
1 2 3 4 5 6