Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Merge two sorted arrays
Next article icon

Merging two unsorted arrays in sorted order

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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}
Recommended PracticeMerging two unsorted arrays in sorted orderTry It!

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. 

Implementation:

C++




// 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;
}
 
 

Java




// 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. 
 
 

Python3




# 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],end=" ")
      
# This code is contributed by Sachin Bisht    
 
 

C#




// 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.
 
 

PHP




<?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.
?>
 
 

Javascript




<script>
  
// Javascript program to merge two unsorted lists
// in sorted order
  
// Function to merge array in sorted order
function sortedMerge(a, b, res,
                                n, m)
{
    // Sorting a[] and b[]
    a.sort((a,b) => a-b);
    b.sort((a,b) => a-b);
  
    // Merge two sorted arrays into res[]
    let 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
  
    let a = [ 10, 5, 15 ];
    let b = [ 20, 3, 2, 12 ];
    let n = a.length;
    let m = b.length;
  
    // Final merge list
    let res = new Array(n + m);
  
    sortedMerge(a, b, res, n, m);
  
    document.write("Sorted merge list :");
    for (let i = 0; i < n + m; i++)
        document.write(" " + res[i]);
  
  
//This code is contributed by Mayank Tyagi
</script>
 
 
Output
Sorted merged list : 2 3 5 10 12 15 20n

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.  

Implementation:

C++




// 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;
}
 
 

Java




// 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.
 
 

Python3




# 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],end=" ")
      
# This code is contributed by Sachin Bisht    
 
 

C#




// 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.
 
 

Javascript




<script>
  
// JavaScript program to merge two unsorted 
// lists in sorted order
  
// Function to merge array in sorted order
function sortedMerge(a, b, res, n, m)
{
      
    // Sorting a[] and b[]
    a.sort((a, b) => a - b);
    b.sort((a, b) => a - b);
  
    // Merge two sorted arrays into res[]
    let 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;
        }
    }
      
    // Merging remaining
    // elements of a[] (if any)
    while (i < n) 
    {
        res[k] = a[i];
        i += 1;
        k += 1;
    }
      
    // Merging remaining
    // elements of b[] (if any)
    while (j < m)
    { 
        res[k] = b[j];
        j += 1;
        k += 1;
    }
}
  
// Driver code
let a = [ 10, 5, 15 ];
let b = [ 20, 3, 2, 12 ];
let n = a.length;
let m = b.length;
  
// Final merge list
let res = new Array(n + m);
  
sortedMerge(a, b, res, n, m);
  
document.write("Sorted merge list :");
for(let i = 0; i < n + m; i++)
    document.write(" " + res[i]);
  
// This code is contributed by Surbhi Tyagi.
  
</script>
 
 
Output
Sorted merge list : 2 3 5 10 12 15 20n

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.

 



Next Article
Merge two sorted arrays
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • Sorting
Practice Tags :
  • Arrays
  • Sorting

Similar Reads

  • Sorted merge in one array
    Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two
    7 min read
  • Merging and Sorting Two Unsorted Stacks
    Given 2 input stacks with elements in an unsorted manner. Problem is to merge them into a new final stack, such that the elements become arranged in a sorted manner. Examples: Input : s1 : 9 4 2 1 s2: 8 17 3 10 Output : final stack: 1 2 3 4 8 9 10 17 Input : s1 : 5 7 2 6 4 s2 : 12 9 3 Output : final
    6 min read
  • Merge two sorted arrays
    Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content [Naive Approach] Concaten
    10 min read
  • Merge two sorted arrays in Python using heapq
    Given two sorted arrays, the task is to merge them in a sorted manner. Examples: Input : arr1 = [1, 3, 4, 5] arr2 = [2, 4, 6, 8] Output : arr3 = [1, 2, 3, 4, 4, 5, 6, 8] Input : arr1 = [5, 8, 9] arr2 = [4, 7, 8] Output : arr3 = [4, 5, 7, 8, 8, 9] This problem has existing solution please refer Merge
    2 min read
  • Intersection of Two Sorted Arrays
    Given two sorted arrays a[] and b[], the task is to return intersection. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in sorted order. Examples: Input: a[] = {1, 1, 2, 2, 2,
    12 min read
  • Union of Two Sorted Arrays
    Given two sorted arrays a[] and b[], the task is to to return union of both the arrays in sorted order. Union of two arrays is an array having all distinct elements that are present in either array. The input arrays may contain duplicates. Examples: Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4
    15+ min read
  • Union of Two Sorted Arrays with Distinct Elements
    Given two sorted arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in sorted order. Note: Union of two arrays is an array having all distinct elements that are present in either array. Examples: Input: a[] = {1, 2, 3}, b[] = {2, 5, 7}Output: {1, 2, 3, 5, 7}Exp
    15+ min read
  • Merge two sorted arrays using Priority queue
    Given two sorted arrays A[] and B[] of sizes N and M respectively, the task is to merge them in a sorted manner. Examples: Input: A[] = { 5, 6, 8 }, B[] = { 4, 7, 8 }Output: 4 5 6 7 8 8 Input: A[] = {1, 3, 4, 5}, B] = {2, 4, 6, 8} Output: 1 2 3 4 4 5 6 8 Input: A[] = {5, 8, 9}, B[] = {4, 7, 8} Outpu
    6 min read
  • Sort a nearly sorted (or K sorted) array
    Given an array arr[] and a number k . The array is sorted in a way that every element is at max k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i - k to i + k where i is index in the given array. Our task is to completely s
    6 min read
  • Merge Two Sorted Arrays Without Extra Space
    Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order. Examples: Input: a[] = [2, 4,
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences