VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-sorted-arrays-using-priority-queue/

⇱ Merge two sorted arrays using Priority queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted arrays using Priority queue

Last Updated : 23 Jul, 2025

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: 

Below is the implementation of the above approach:


Output
4 5 6 7 8 8 

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

Comment