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 Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Merge k Sorted Arrays Using Min Heap
Next article icon

Merge two sorted arrays using Priority queue

Last Updated : 18 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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} 
Output: 4 5 7 8 8 9 

Approach: The given problem, merging two sorted arrays using minheap already exists. But here the idea is to use a priority_queue to implement min-heap provided by STL. Follow the steps below to solve the problem: 

  • Initialize a min priority queue say PQ to implement the Min Heap.
  • Traverse the array A[], and push all the elements of the array into the PQ.
  • Traverse the array B[], and push all the elements of the array into the PQ.
  • Now put all the elements of the PQ into an array, say res[] popping the top element of the PQ one by one.
  • Finally, print the sorted array res[] as the answer.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to merge two arrays
void merge(int A[], int B[], int N, int M)
{
    // Stores the merged array
    int res[N + M];
 
    // Create a min priority_queue
    priority_queue<int, vector<int>, greater<int> > pq;
 
    // Traverse the array A[]
    for (int i = 0; i < N; i++)
        pq.push(A[i]);
 
    // Traverse the array B[]
    for (int i = 0; i < M; i++)
        pq.push(B[i]);
 
    int j = 0;
 
    // Iterate until the
    // pq is not empty
    while (!pq.empty()) {
 
        // Stores the top element
        // of pq into res[j]
        res[j++] = pq.top();
 
        // Removes the top element
        pq.pop();
    }
 
    // Print the merged array
    for (int i = 0; i < N + M; i++)
        cout << res[i] << ' ';
}
 
// Driver Code
int main()
{
 
    // Input
    int A[] = { 5, 6, 8 };
    int B[] = { 4, 7, 8 };
 
    int N = sizeof(A) / sizeof(A[0]);
    int M = sizeof(B) / sizeof(B[0]);
 
    // Function call
    merge(A, B, N, M);
 
    return 0;
}
 
 

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to merge two arrays
static void merge(int A[], int B[], int N, int M)
{
     
    // Stores the merged array
    int []res = new int[N + M];
     
    // Create a min priority_queue
    Queue<Integer> pq = new PriorityQueue<>();
     
    // Traverse the array A[]
    for(int i = 0; i < N; i++)
        pq.add(A[i]);
     
    // Traverse the array B[]
    for(int i = 0; i < M; i++)
        pq.add(B[i]);
     
    int j = 0;
     
    // Iterate until the
    // pq is not empty
    while (!pq.isEmpty())
    {
         
        // Stores the top element
        // of pq into res[j]
        res[j++] = pq.peek();
     
        // Removes the top element
        pq.remove();
    }
     
    // Print the merged array
    for(int i = 0; i < N + M; i++)
        System.out.print(res[i] + " ");
}
 
// Driver Code
public static void main(String[] args)
{
     
    // Input
    int A[] = { 5, 6, 8 };
    int B[] = { 4, 7, 8 };
 
    int N = A.length;
    int M = B.length;
 
    // Function call
    merge(A, B, N, M);
}
}
 
// This code is contributed by todaysgaurav
 
 

Python3




# Python3 program for the above approach
from queue import PriorityQueue
 
# Function to merge two arrays
def merge(A, B, N, M):
 
    # Stores the merged array
    res = [0 for i in range(N + M)]
     
    # Create a min priority_queue
    pq = PriorityQueue()
     
    # Traverse the array A[]
    for i in range(N):
        pq.put(A[i])
         
    # Traverse the array B[]
    for i in range(M):
        pq.put(B[i])
 
    j = 0
     
    # Iterate until the
    # pq is not empty
    while not pq.empty():
       
        # Removes the top element and
        # stores it into res[j]
        res[j] = pq.get()
        j += 1
         
    # Print the merged array
    for i in range(N + M):
        print(res[i], end = " ")
         
    # return back to main
    return
 
# Driver code
if __name__ == '__main__':
   
    # Input
    A = [ 5, 6, 8 ]
    B = [ 4, 7, 8 ]
 
    N = len(A)
    M = len(B)
     
    # Function call
    merge(A, B, N, M)
     
# This code is contributed by MuskanKalra1
 
 

C#




// C# program for the above approach.
using System;
using System.Collections.Generic;
 
public class GFG {
  public static int cmp(int a, int b) { return a - b; }
 
  // Function to merge two arrays
  static void merge(int[] A, int[] B, int N, int M)
  {
    // Stores the merged array
    int[] res = new int[N + M];
 
    // Create a min priority_queue using List and cmp
    // comparator
    List<int> pq = new List<int>();
 
    // Traverse the array A[]
    for (int i = 0; i < N; i++)
      pq.Add(A[i]);
 
    // Traverse the array B[]
    for (int i = 0; i < M; i++)
      pq.Add(B[i]);
 
    int j = 0;
 
    pq.Sort(cmp);
 
    // Iterate until the
    // pq is not empty
    int index = 0;
    while (index < pq.Count) {
 
      // Stores the top element
      // of pq into res[j]
      res[j++] = pq[index];
 
      // Removes the top element
      index++;
    }
 
    // Print the merged array
    for (int i = 0; i < N + M; i++)
      Console.Write(res[i] + " ");
  }
 
  public static void Main(string[] args)
  {
    // Input
    int[] A = { 5, 6, 8 };
    int[] B = { 4, 7, 8 };
 
    int N = A.Length;
    int M = B.Length;
 
    // Function call
    merge(A, B, N, M);
  }
}
 
// This code is contributed by adityamaharshi21.
 
 

Javascript




<script>
 
// Javascript program for the above approach
 
// Function to merge two arrays
function merge(A, B, N, M)
{
 
    // Stores the merged array
    var res = Array(N+M).fill(0);
 
    // Create a min priority_queue
    var pq = [];
 
    // Traverse the array A[]
    for (var i = 0; i < N; i++)
        pq.push(A[i]);
 
    // Traverse the array B[]
    for (var i = 0; i < M; i++)
        pq.push(B[i]);
 
    var j = 0;
    pq.sort((a,b)=>b-a);
 
    // Iterate until the
    // pq is not empty
    while (pq.length!=0) {
 
        // Stores the top element
        // of pq into res[j]
        res[j++] = pq[pq.length-1];
 
        // Removes the top element
        pq.pop();
        pq.sort((a,b)=>b-a);
    }
 
    // Print the merged array
    for (var i = 0; i < N + M; i++)
        document.write(res[i] + ' ');
}
 
// Driver Code
// Input
var A = [5, 6, 8];
var B = [4, 7, 8];
var N = A.length;
var M = B.length;
 
// Function call
merge(A, B, N, M);
 
// This code is contributed by rrrtnx.
</script>
 
 
Output
4 5 6 7 8 8 

Time Complexity: O((N+M)*log(N+M))
Auxiliary Space: O(N+M)



Next Article
Merge k Sorted Arrays Using Min Heap
author
srivastavaharshit848
Improve
Article Tags :
  • Arrays
  • DSA
  • Queue
  • Sorting
  • Brocade
  • Goldman Sachs
  • Juniper
  • Linkedin
  • Microsoft
  • priority-queue
  • Quikr
  • Snapdeal
  • Synopsys
  • Zoho
Practice Tags :
  • Brocade
  • Goldman Sachs
  • Linkedin
  • Microsoft
  • Quikr
  • Snapdeal
  • Synopsys
  • Zoho
  • Arrays
  • priority-queue
  • Queue
  • Sorting

Similar Reads

  • Priority Queue Using Array
    A priority queue is a data structure that stores elements with associated priorities. In a priority queue, elements are dequeued in order of their priority, with the highest priority elements being removed first. It is commonly used in algorithms like Dijkstra's for shortest path and in real-time sc
    8 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
  • 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
  • How to implement Priority Queue - using Heap or Array?
    A Priority Queue is a data structure that allows you to insert elements with a priority, and retrieve the element with the highest priority. You can implement a priority queue using either an array or a heap. Both array and heap-based implementations of priority queues have their own advantages and
    15+ min read
  • Merge k Sorted Arrays Using Min Heap
    Given k sorted arrays of possibly different sizes, merge them and print the sorted output.Examples: Input: k = 3 arr[][] = { {1, 3}, {2, 4, 6}, {0, 9, 10, 11}} ;Output: 0 1 2 3 4 6 9 10 11 Input: k = 2 arr[][] = { {1, 3, 20}, {2, 4, 6}} ;Output: 1 2 3 4 6 20 We have discussed a solution that works f
    7 min read
  • Priority Queue using Binary Heap
    What is a Priority Queue ?Priority Queue is an extension of the queue with the following properties: Every item has a priority associated with it.An element with high priority is dequeued before an element with low priority.If two elements have the same priority, they are served according to their o
    15+ min read
  • 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,
    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
  • Print uncommon elements from two sorted arrays
    Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order. Examples : Input : arr1[] = {10, 20, 30} arr2[] = {20, 25, 30, 40, 50} Output : 10 25 40 50 We do not print 20 and 30 as these elements ar
    6 min read
  • Turn a Queue into a Priority Queue
    What is Queue?Queue is an abstract data type that is open at both ends. One end is always used to insert data (enqueue) which is basically the rear/back/tail end and the other which is the front end is used to remove data (dequeue). Queue follows First-In-First-Out (FIFO) methodology, i.e., "the dat
    9 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