Solved Problem - Merge Sorted Arrays

In this lesson, we'll discuss how to merge two sorted arrays.

Problem statement

Given two sorted arrays, A[]A[] and B[]B[], of sizes NN and MM respectively, merge them into a single array of size N+MN+M and print the array.

Input format

The first line consists of two space-separated integers N,MN, M (1N,M105)(1 \leq N,M \leq10^5).

The second line consists of NN space-separated integers representing the array A[]A[] (1A[i]105)(1 \leq A[i] \leq 10^5).

The third line consists of MM space-separated integers representing the array B[]B[] (1B[i]105)(1 \leq B[i] \leq 10^5).

Output format

Print a single line of output containing the N+MN+M integers representing the merged and sorted array C[]C[].


Sample

Input:

4 4
2 3 4 6
1 5 7 8

Output

1 2 3 4 5 6 7 8

Solution

We use 2 pointers ii and jj for A[]A[] and B[]B[] respectively.

At each step, we copy the smaller of A[i],B[j]A[i], B[j] to the current end of C[]C[]. Keep doing this until we reach the end of A or B. After that only one array remains (either AA or BB), copy all the remaining elements to C.

See the illustration for better understanding.

Get hands-on with 1200+ tech skills courses.