Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Approach-1
3.
Approach-2
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Merge Two Unsorted Arrays

Author Akash Nagpal
0 upvote

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;  
}  
You can also try this code with Online C++ Compiler
Run Code

Output

The sorted array is:  8 12 13 21 23 33 40 57 57 75 100
You can also try this code with Online C++ Compiler
Run Code

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 method can be improved by sorting first and then combining it with the third array. Separately sort both arrays before merging them into the final array.

C++ Code

#include <bits/stdc++.h>  
using namespace std;  
// Function for Merge two arrays in unsorted manner
void sortedMerge(int a[], int b[], int res[],  
    int n, int m)   
{  
    sort(a, a + n); // sorting array a   
    sort(b, b + m); // sorting array b   
  
  
    int i = 0, j = 0, k = 0; 
    // After sorting, compare and merge elements to third array
    while (i < n && j < m) {    
        if (a[i] <= b[j]) {    
            res[k] = a[i];    
            i += 1;  
            k += 1;  
        } 
        else 
        {
            // otherwise putting the elements of b into res array and incrementing j
            res[k] = b[j]; 
            j += 1;  
            k += 1;  
        }  
    } 
    // If array a elements are left putting them in res 
    while (i < n) {  
        res[k] = a[i];  
        i += 1;  
        k += 1;  
    }  
    while (j < m) { // If array b elements are left putting them in res  
        res[k] = b[j];  
        j += 1;  
        k += 1;  
    }  
}  
  
int main()  
{  
    int a[] = { 50, 95, 35, 12, 100 };  
    int b[] = { 10, 43, 23, 33, 9, 17 };  
    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;  
}  
You can also try this code with Online C++ Compiler
Run Code

Output

The sorted array is:  9 10 12 17 23 33 35 43 50 95 100
You can also try this code with Online C++ Compiler
Run Code

Time Complexity: O (nlogn + mlogm + (n + m)) it is better than approach 1

Space Complexity: O ( (n + m) ) It remains same as approach 1

You can try by yourself with the help of online C++ Compiler.

Also read - Decimal to Binary c++

FAQs

  1. What is logarithmic(log) time complexity?
    Since each extra piece of data takes less time to process than the previous one, logarithmic complexity means that the time to finish rises more slowly than the input size: to raise the runtime by a constant amount, you must increase the input size exponentially.
     
  2. What do you mean by linear time complexity in data structures?
    The time to finish is generally proportional to the input quantity. Each extra bit of input causes, a constant rise in runtime since each additional bit of information takes roughly the same amount of time to process.

Key Takeaways

In this article, we have extensively discussed the program to merge two unsorted arrays using two approaches. We tried to cover it with some examples.

You can look at more exciting blogs and articles curated by the coding ninja's team by visiting Library.

We hope that this blog has helped you enhance your knowledge regarding Merging arrays in C++ and if you would like to learn more, check out our articles on Arrays in C++

Recommended Problem - Merge K Sorted Arrays

Do upvote our blog to help other ninjas grow. 

Happy Coding!

 

Live masterclass