Solved Problem - Merge Sorted Arrays
In this lesson, we'll discuss how to merge two sorted arrays.
We'll cover the following
Problem statement
Given two sorted arrays, and , of sizes and respectively, merge them into a single array of size and print the array.
Input format
The first line consists of two space-separated integers .
The second line consists of space-separated integers representing the array .
The third line consists of space-separated integers representing the array .
Output format
Print a single line of output containing the integers representing the merged and sorted array .
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 and for and respectively.
At each step, we copy the smaller of to the current end of . Keep doing this until we reach the end of A or B. After that only one array remains (either or ), copy all the remaining elements to C.
See the illustration for better understanding.
Get hands-on with 1400+ tech skills courses.