Dadas k arrays ordenadas de tamaños posiblemente diferentes, combínelas e imprima la salida ordenada.
Ejemplos:
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
Hemos discutido una solución que funciona para todas las arrays del mismo tamaño en Merge k sorted arrays | conjunto 1 .
Una solución simple es crear una array de salida y, una por una, copiar todas las arrays k en ella. Finalmente, ordene la array de salida. Este enfoque toma el tiempo O(N Log N) donde N es el conteo de todos los elementos.
Una solución eficiente es utilizar una estructura de datos de montón. La complejidad de tiempo de la solución basada en almacenamiento dinámico es O(N Log k).
1. Cree una array de salida.
2. Cree un montón mínimo de tamaño k e inserte el primer elemento en todas las arrays en el montón
. 3. Repita los siguientes pasos mientras la cola de prioridad no esté vacía.
…..a) Eliminar el elemento mínimo del montón (el mínimo siempre está en la raíz) y almacenarlo en la array de salida.
…..b) Inserte el siguiente elemento de la array de la que se extrae el elemento. Si la array no tiene más elementos, no haga nada.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to merge k sorted arrays // of size n each. #include <bits/stdc++.h> using namespace std; // A pair of pairs, first element is going to // store value, second element index of array // and third element index in the array. typedef pair<int, pair<int, int> > ppi; // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It merges them together and prints // the final sorted output. vector<int> mergeKArrays(vector<vector<int> > arr) { vector<int> output; // Create a min heap with k heap nodes. Every // heap node has first element of an array priority_queue<ppi, vector<ppi>, greater<ppi> > pq; for (int i = 0; i < arr.size(); i++) pq.push({ arr[i][0], { i, 0 } }); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.empty() == false) { ppi curr = pq.top(); pq.pop(); // i ==> Array Number // j ==> Index in the array number int i = curr.second.first; int j = curr.second.second; output.push_back(curr.first); // The next element belongs to same array as // current. if (j + 1 < arr[i].size()) pq.push({ arr[i][j + 1], { i, j + 1 } }); } return output; } // Driver program to test above functions int main() { // Change n at the top to change number // of elements in an array vector<vector<int> > arr{ { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; vector<int> output = mergeKArrays(arr); cout << "Merged array is " << endl; for (auto x : output) cout << x << " "; return 0; }
Java
/*package whatever //do not write package name here */ import java.util.ArrayList; import java.util.PriorityQueue; public class MergeKSortedArrays { private static class HeapNode implements Comparable<HeapNode> { int x; int y; int value; HeapNode(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } @Override public int compareTo(HeapNode hn) { if (this.value <= hn.value) { return -1; } else { return 1; } } } // Function to merge k sorted arrays. public static ArrayList<Integer> mergeKArrays(int[][] arr, int K) { ArrayList<Integer> result = new ArrayList<Integer>(); PriorityQueue<HeapNode> heap = new PriorityQueue<HeapNode>(); // Initially add only first column of elements. First // element of every array for (int i = 0; i < arr.length; i++) { heap.add(new HeapNode(i, 0, arr[i][0])); } HeapNode curr = null; while (!heap.isEmpty()) { curr = heap.poll(); result.add(curr.value); // Check if next element of curr min exists, // then add that to heap. if (curr.y < (arr[curr.x].length - 1)) { heap.add( new HeapNode(curr.x, curr.y + 1, arr[curr.x][curr.y + 1])); } } return result; } public static void main(String[] args) { int[][] arr = { { 2, 6, 12 }, { 1, 9 }, { 23, 34, 90, 2000 } }; System.out.println( MergeKSortedArrays.mergeKArrays(arr, arr.length) .toString()); } } // This code has been contributed by Manjunatha KB
Python3
# merge function merge two arrays # of different or same length # if n = max(n1, n2) # time complexity of merge is (o(n log(n))) from heapq import merge # function for meging k arrays def mergeK(arr, k): l = arr[0] for i in range(k-1): # when k = 0 it merge arr[1] # with arr[0] here in l arr[0] # is stored l = list(merge(l, arr[i + 1])) return l # for printing array def printArray(arr): print(*arr) # driver code arr =[[2, 6, 12 ], [ 1, 9 ], [23, 34, 90, 2000 ]] k = 3 l = mergeK(arr, k) printArray(l)
C#
// C# program to merge k sorted arrays // of size n each. using System; using System.Collections.Generic; class GFG { // This function takes an array of arrays as an // argument and all arrays are assumed to be // sorted. It merges them together and prints // the final sorted output. static List<int> mergeKArrays(List<List<int>> arr) { List<int> output = new List<int>(); // Create a min heap with k heap nodes. Every // heap node has first element of an array List<Tuple<int,Tuple<int,int>>> pq = new List<Tuple<int,Tuple<int,int>>>(); for (int i = 0; i < arr.Count; i++) pq.Add(new Tuple<int, Tuple<int,int>>(arr[i][0], new Tuple<int,int>(i, 0))); pq.Sort(); // Now one by one get the minimum element // from min heap and replace it with next // element of its array while (pq.Count > 0) { Tuple<int,Tuple<int,int>> curr = pq[0]; pq.RemoveAt(0); // i ==> Array Number // j ==> Index in the array number int i = curr.Item2.Item1; int j = curr.Item2.Item2; output.Add(curr.Item1); // The next element belongs to same array as // current. if (j + 1 < arr[i].Count) { pq.Add(new Tuple<int,Tuple<int,int>>(arr[i][j + 1], new Tuple<int,int>(i, j + 1))); pq.Sort(); } } return output; } // Driver code static void Main() { // Change n at the top to change number // of elements in an array List<List<int>> arr = new List<List<int>>(); arr.Add(new List<int>(new int[]{2, 6, 12})); arr.Add(new List<int>(new int[]{1, 9})); arr.Add(new List<int>(new int[]{23, 34, 90, 2000})); List<int> output = mergeKArrays(arr); Console.WriteLine("Merged array is "); foreach(int x in output) Console.Write(x + " "); } } // This code is contributed by divyeshrabadiya07.
Merged array is 1 2 6 9 12 23 34 90 2000
Complejidad de Tiempo: O(N Log k)
Espacio Auxiliar: O(N)