C++ program to merge two unsorted arrays

In this article, we will write a program to merge two unsorted arrays. The output is the sorted array in ascending order.

Input : a[] = {10, 5, 15}

b[] = {20, 3, 2}

Output : The merged array in sorted order {2, 3, 5, 10, 15, 20}

Input : a[] = {1, 10, 5, 15}

b[] = {20, 0, 2}

Output : The merged array in sorted order {0, 1, 2, 5, 10, 15, 20}

Approach 1

The first approach that can be used here is to concatenate both the arrays and sort the concatenated array. We create a third array of the size of the first two arrays and then transfer all the elements of both the arrays into the resultant array. After the append operation, we sort the resultant array.

C code

Output

The sorted array is:  1 2 3 5 7 10 12 15 20 22 100

Time complexity

O((n+m)log(n+m), where n and m are the sizes of the arrays

Space complexity

O(n+m)

Approach 2

The above approach can be optimised when we use the idea of first sorting then merging it to the third array. Sort both the arrays separately and merge them into the resultant array.

C code

Output

The sorted array is:  1 2 3 5 7 10 12 15 20 22 100

Time Complexity:

O (nlogn + mlogm + (n + m)) // which is far better than approach 1

Space Complexity:

O ( (n + m) ) It remains same as the approach 1






Latest Courses