Merge k sorted arrays of different sizes in C++



Suppose we have different k sorted arrays. We have to merge these arrays and display the sorted result.

So, if the input is like k = 3 and arrays are {2, 4},{3, 5, 7},{1, 10, 11, 12} , then the output will be 1 2 3 4 5 7 10 11 12

To solve this, we will follow these steps −

  • define one type of pair with first element is an integer and second element is another pair of integers, name it as ppi.
  • Define an array op
  • define one priority queue q
  • for initialize i := 0, when i < size of arr, update (increase i by 1), do −
    • insert (arr[i, 0], {i, 0} )into q
  • while q is not empty, do −
    • current_element := top element of q
    • delete element from q
    • i := second element from current_element
    • j := third element from current_element
    • insert first element of current_element at the end of op
    • if j + 1 < size of arr[i], then &minus
      • insert (arr[i, j+1], {i, j+1} )into q
  • return op

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h> using namespace std; #define ppi pair<int,pair<int,int>> vector<int> merge(vector<vector<int> > arr){    vector<int> op;    priority_queue<ppi, vector<ppi>, greater<ppi> > queue;    for (int i = 0; i < arr.size(); i++)    queue.push({ arr[i][0], { i, 0 } });    while (queue.empty() == false) {       ppi current_element = queue.top();       queue.pop();       int i = current_element.second.first;       int j = current_element.second.second;       op.push_back(current_element.first);       if (j + 1 < arr[i].size())       queue.push({ arr[i][j + 1], { i, j + 1 } });    }    return op; } int main(){    vector<vector<int> > arr{ { 2,4}, { 3,5,7 }, { 1, 10, 11, 12 } };    vector<int> output = merge(arr);    for(int i = 0; i<output.size(); i++)    cout << output[i] << " "; }

Input

{{ 2,4}, { 3,5,7 }, { 1, 10, 11, 12 }}

Output

1 2 3 4 5 7 10 11 12
Updated on: 2020-08-27T12:12:12+05:30

620 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements