Merging two unsorted arrays in sorted order

Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.

Examples :

Input : a[] = {10, 5, 15}
        b[] = {20, 3, 2}
Output : Merge List :
        {2, 3, 5, 10, 15, 20}

Input : a[] = {1, 10, 5, 15}
        b[] = {20, 0, 2}
Output : Merge List :
        {0, 1, 2, 5, 10, 15, 20}

There are many cases to deal with: either ‘a’ or ‘b’ may be empty, during processing either ‘a’ or ‘b’ may run out first, and finally there’s the problem of starting the result list empty, and building it up while going through ‘a’ and ‘b’.

Method 1 (first Concatenate then Sort)

In this case, we first append the two unsorted lists. Then we simply sort the concatenated list.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to merge two unsorted lists 
// in sorted order
#include <bits/stdc++.h>
using namespace std;
  
// Function to merge array in sorted order
void sortedMerge(int a[], int b[], int res[], 
                                int n, int m)
{
    // Concatenate two arrays
    int i = 0, j = 0, k = 0;
    while (i < n) {
        res[k] = a[i];
        i += 1;
        k += 1;
    }
    while (j < m) {
        res[k] = b[j];
        j += 1;
        k += 1;
    }
  
    // sorting the res array
    sort(res, res + n + m);
}
  
// Driver code
int main()
{
    int a[] = { 10, 5, 15 };
    int b[] = { 20, 3, 2, 12 };
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
  
    // Final merge list
    int res[n + m];
    sortedMerge(a, b, res, n, m);
  
    cout << "Sorted merged list :";
    for (int i = 0; i < n + m; i++)
        cout << " " << res[i];
    cout << "n";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Code for Merging two unsorted
// arrays in sorted order
import java.util.*;
  
class GFG {
  
    // Function to merge array in sorted order
    public static void sortedMerge(int a[], int b[], 
                                   int res[], int n, 
                                   int m)
    {
        // Concatenate two arrays
        int i = 0, j = 0, k = 0;
        while (i < n) {
            res[k] = a[i];
            i++;
            k++;
        }
          
        while (j < m) {
            res[k] = b[j];
            j++;
            k++;
        }
      
        // sorting the res array
        Arrays.sort(res);
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int a[] = { 10, 5, 15 };
        int b[] = { 20, 3, 2, 12 };
        int n = a.length;
        int m = b.length;
      
        // Final merge list
        int res[]=new int[n + m];
        sortedMerge(a, b, res, n, m);
      
        System.out.print("Sorted merged list :");
        for (int i = 0; i < n + m; i++)
            System.out.print(" " + res[i]); 
    }
}
  
// This code is contributed by Arnav Kr. Mandal. 

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to merge two unsorted lists 
# in sorted order
  
# Function to merge array in sorted order
def sortedMerge(a, b, res, n, m):
    # Concatenate two arrays
    i, j, k = 0, 0, 0
    while (i < n):
        res[k] = a[i]
        i += 1
        k += 1
    while (j < m):
        res[k] = b[j]
        j += 1
        k += 1
   
    # sorting the res array
    res.sort()
   
# Driver code
a = [ 10, 5, 15 ]
b = [ 20, 3, 2, 12 ]
n = len(a)
m = len(b)
  
# Final merge list
res = [0 for i in range(n + m)]
sortedMerge(a, b, res, n, m)
print "Sorted merged list :"
for i in range(n + m):
    print res[i],
      
# This code is contributed by Sachin Bisht    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Code for Merging two 
// unsorted arrays in sorted order
using System;
  
class GFG {
  
    // Function to merge array in sorted order
    public static void sortedMerge(int []a, int []b, 
                                   int []res, int n, 
                                   int m)
    {
        // Concatenate two arrays
        int i = 0, j = 0, k = 0;
        while (i < n) {
            res[k] = a[i];
            i++;
            k++;
        }
          
        while (j < m) {
            res[k] = b[j];
            j++;
            k++;
        }
      
        // sorting the res array
        Array.Sort(res);
    }
      
    /* Driver program to test above function */
    public static void Main() 
    {
        int []a = {10, 5, 15};
        int []b = {20, 3, 2, 12};
        int n = a.Length;
        int m = b.Length;
      
        // Final merge list
        int []res=new int[n + m];
        sortedMerge(a, b, res, n, m);
      
        Console.Write("Sorted merged list :");
        for (int i = 0; i < n + m; i++)
            Console.Write(" " + res[i]); 
    }
}
  
// This code is contributed by nitin mittal.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to merge two unsorted lists 
// in sorted order 
  
// Function to merge array in sorted order 
function sortedMerge($a, $b, $n, $m
    // Concatenate two arrays 
    $res = array();
    $i = 0; $j = 0; $k = 0; 
    while ($i < $n
    
        $res[$k] = $a[$i]; 
        $i += 1; 
        $k += 1; 
    
    while ($j < $m)
    
        $res[$k] = $b[$j]; 
        $j += 1; 
        $k += 1; 
    
  
    // sorting the res array 
    sort($res); 
    echo "Sorted merged list :"
      
    for ($i = 0; $i < count($res); $i++) 
        echo $res[$i] . " "
  
// Driver code 
$a = array( 10, 5, 15 ); 
$b = array( 20, 3, 2, 12 ); 
$n = count($a); 
$m = count($b); 
  
// Final merge list 
  
sortedMerge($a, $b, $n, $m); 
  
// This code is contributed by Rajput-Ji.
?>

chevron_right



Output :

Sorted merged list : 2 3 5 10 12 15 20

Time Complexity : O ( (n + m) (log(n + m)) )
Auxiliary Space : O ( (n + m) )

 

Method 2 (First Sort then Merge)

We first sort both the given arrays separately. Then we simply merge two sorted arrays.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to merge two unsorted lists 
// in sorted order
#include <bits/stdc++.h>
using namespace std;
  
// Function to merge array in sorted order
void sortedMerge(int a[], int b[], int res[], 
                                int n, int m)
{
    // Sorting a[] and b[]
    sort(a, a + n);
    sort(b, b + m);
  
    // Merge two sorted arrays into res[]
    int i = 0, j = 0, k = 0;
    while (i < n && j < m) {
        if (a[i] <= b[j]) {
            res[k] = a[i];
            i += 1;
            k += 1;
        } else {
            res[k] = b[j];
            j += 1;
            k += 1;
        }
    }    
    while (i < n) {  // Merging remaining
                     // elements of a[] (if any)
        res[k] = a[i];
        i += 1;
        k += 1;
    }    
    while (j < m) {   // Merging remaining
                     // elements of b[] (if any)
        res[k] = b[j];
        j += 1;
        k += 1;
    }
}
  
// Driver code
int main()
{
    int a[] = { 10, 5, 15 };
    int b[] = { 20, 3, 2, 12 };
    int n = sizeof(a) / sizeof(a[0]);
    int m = sizeof(b) / sizeof(b[0]);
  
    // Final merge list
    int res[n + m];
  
    sortedMerge(a, b, res, n, m);
  
    cout << "Sorted merge list :";
    for (int i = 0; i < n + m; i++)
        cout << " " << res[i];
    cout << "n";
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// JAVA Code for Merging two unsorted 
// arrays in sorted order
import java.util.*;
  
class GFG {
      
    // Function to merge array in sorted order
    public static void sortedMerge(int a[], int b[],
                                  int res[], int n,
                                            int m)
    {
        // Sorting a[] and b[]
        Arrays.sort(a);
        Arrays.sort(b);
       
        // Merge two sorted arrays into res[]
        int i = 0, j = 0, k = 0;
        while (i < n && j < m) {
            if (a[i] <= b[j]) {
                res[k] = a[i];
                i += 1;
                k += 1;
            } else {
                res[k] = b[j];
                j += 1;
                k += 1;
            }
        }    
          
        while (i < n) {  // Merging remaining
                         // elements of a[] (if any)
            res[k] = a[i];
            i += 1;
            k += 1;
        }    
        while (j < m) {   // Merging remaining
                         // elements of b[] (if any)
            res[k] = b[j];
            j += 1;
            k += 1;
        }
    }
      
    /* Driver program to test above function */
    public static void main(String[] args) 
    {
        int a[] = { 10, 5, 15 };
        int b[] = { 20, 3, 2, 12 };
        int n = a.length;
        int m = b.length;
       
        // Final merge list
        int res[] = new int[n + m];
        sortedMerge(a, b, res, n, m);
       
        System.out.print( "Sorted merged list :");
        for (int i = 0; i < n + m; i++)
            System.out.print(" " + res[i]);   
    }
}
// This code is contributed by Arnav Kr. Mandal.

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to merge two unsorted lists 
# in sorted order
  
# Function to merge array in sorted order
def sortedMerge(a, b, res, n, m):
    # Sorting a[] and b[]
    a.sort()
    b.sort()
      
    # Merge two sorted arrays into res[]
    i, j, k = 0, 0, 0
    while (i < n and j < m):
        if (a[i] <= b[j]):
            res[k] = a[i]
            i += 1
            k += 1
        else:
            res[k] = b[j]
            j += 1
            k += 1
              
    while (i < n):  # Merging remaining
                    # elements of a[] (if any)
        res[k] = a[i]
        i += 1
        k += 1
          
    while (j < m):  # Merging remaining
                    # elements of b[] (if any)
        res[k] = b[j]
        j += 1
        k += 1
   
# Driver code
a = [ 10, 5, 15 ]
b = [ 20, 3, 2, 12 ]
n = len(a)
m = len(b)
  
# Final merge list
res = [0 for i in range(n + m)]
sortedMerge(a, b, res, n, m)
print "Sorted merged list :"
for i in range(n + m):
    print res[i],
      
# This code is contributed by Sachin Bisht    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Code for Merging two unsorted 
// arrays in sorted order
using System; 
  
class GFG {
      
    // Function to merge array in 
    // sorted order
    static void sortedMerge(int []a, int []b,
                     int []res, int n, int m)
    {
          
        // Sorting a[] and b[]
        Array.Sort(a);
        Array.Sort(b);
      
        // Merge two sorted arrays into res[]
        int i = 0, j = 0, k = 0;
          
        while (i < n && j < m)
        {
            if (a[i] <= b[j])
            {
                res[k] = a[i];
                i += 1;
                k += 1;
            
            else 
            {
                res[k] = b[j];
                j += 1;
                k += 1;
            }
        
          
        while (i < n)
        
              
            // Merging remaining
            // elements of a[] (if any)
            res[k] = a[i];
            i += 1;
            k += 1;
        
        while (j < m)
        {
              
            // Merging remaining
            // elements of b[] (if any)
            res[k] = b[j];
            j += 1;
            k += 1;
        }
    }
      
    /* Driver program to test
    above function */
    public static void Main() 
    {
        int []a = { 10, 5, 15 };
        int []b = { 20, 3, 2, 12 };
        int n = a.Length;
        int m = b.Length;
      
        // Final merge list
        int []res = new int[n + m];
        sortedMerge(a, b, res, n, m);
      
        Console.Write( "Sorted merged list :");
        for (int i = 0; i < n + m; i++)
            Console.Write(" " + res[i]); 
    }
}
  
// This code is contributed by nitin mittal.

chevron_right



Output :

Sorted merge list : 2 3 5 10 12 15 20

Time Complexity : O (nlogn + mlogm + (n + m))
Space Complexity : O ( (n + m) )

It is obvious from above time complexities that method 2 is better than method 1.

This article is contributed by Sachin Bisht. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : nitin mittal, Rajput-Ji



Article Tags :
Practice Tags :


3


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.