Introduction
In this article, we’ll write a program to merge two unsorted arrays so that the resultant array should be in sorted ascending order.
Here, we will take 2 unsorted arrays with random integer values as an input and our objective is to return a sorted array as output.
Now let us understand the concept of merging with the help of an example.
Example-1
Input : a[] = {13, 7, 15}
b[] = {40, 4, 2}
Output : The merged array in sorted order {2, 4, 7, 13, 15, 40}
Example-2
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 method is to concatenate both arrays and sort the resulting concatenated array.
- We make a third array that has the same size as the first two and then move all of the elements from both arrays into it.
-
We sort the resulting array after the append operation.
C++ Code
#include <bits/stdc++.h>
using namespace std;
// Function to Merge two arrays in unsorted manner
void sortedMerge(int a[], int b[], int res[],
int n, int m)
{
// Concatenating two arrays
int i = 0, j = 0, k = 0;
//Iteration in 1st array
while (i < n)
{
res[k] = a[i]; // putting every element in res array
i += 1;
k += 1;
}
//Iteration In 2nd Array
while (j < m) {
res[k] = b[j]; // putting every element in res array
j += 1;
k += 1;
}
sort(res, res + n + m); // sort the res array
}
int main()
{
int a[] = { 40, 75, 23, 12, 100 };
int b[] = { 8, 13, 57, 33, 21, 57 };
int n = sizeof(a) / sizeof(a[0]); // find the size of array a
int m = sizeof(b) / sizeof(b[0]); // find the size of array b
int res[n + m]; // create res array to Concatenate both the array
sortedMerge(a, b, res, n, m); // call function to append and sort
cout << "The sorted array is: ";
for (int i = 0; i < n + m; i++)
cout << " " << res[i];
cout << "\n";
return 0;
}
Output
The sorted array is: 8 12 13 21 23 33 40 57 57 75 100
Time Complexity: O((n+m)log(n+m), where n and m are the sizes of the arrays
Space Complexity: O(n+m)