Given n machines in the form of the Linked list. Each machine contains some numbers in sorted form. But the amount of numbers, each machine has is not fixed. Output the numbers from all the machine in sorted non-decreasing form.
Examples:
Input: Machine M1 : [30, 40, 50]
Machine M2 : [35, 45]
Machine M3 : [10, 60, 70, 80, 100]
Output: [10, 30, 35, 40, 45, 50, 60, 70, 80, 100]
Explanation: Sorted Number from all Machine is [10, 30, 35, 40, 45, 50, 60, 70, 80, 100]Input: Machine M1 : [1, 5 , 10]
Machine M2 : [35, 45]
Machine M3 : [30, 90, 130]
Output: [1, 5, 10, 30, 35, 45, 90, 130]
Explanation: Sorted Number from all Machine is [1, 5, 10, 30, 35, 45, 90, 130]
[Approach 1] - Using a Priority Queue - Good for Varying-Sized Arrays or Lists
The
mergeListsfunction merges sorted linked lists using a min heap, repeatedly extracting the smallest element and inserting the next node. TheexternalSortfunction converts the linked lists into a vector, callsmergeListsto get the final sorted list, and prints it. Changing the comparison inCompareNodeallows sorting in descending order.
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int data;
ListNode* next;
ListNode(int val) : data(val), next(nullptr) {}
};
struct CompareNode {
bool operator()(const ListNode* a, const ListNode* b) {
return a->data > b->data;
}
};
void push(ListNode*& head, int data) {
ListNode* newNode = new ListNode(data);
newNode->next = head;
head = newNode;
}
void PrintList(ListNode* head) {
while (head) {
cout << head->data;
if (head->next) cout << " ";
head = head->next;
}
cout << endl;
}
ListNode* mergelist(vector<ListNode*>& list) {
priority_queue<ListNode*, vector<ListNode*>, CompareNode> minHeap;
for (auto li : list)
if (li) minHeap.push(li);
ListNode dummy(0), *tail = &dummy;
while (!minHeap.empty()) {
ListNode* node = minHeap.top();
minHeap.pop();
tail->next = node;
tail = tail->next;
if (node->next) minHeap.push(node->next);
}
return dummy.next;
}
ListNode* externalSort(vector<ListNode*>& list) {
ListNode* sortedList = mergelist(list);
return sortedList;
}
int main() {
int N = 3;
vector<ListNode*> list(N, nullptr);
push(list[0], 50);
push(list[0], 40);
push(list[0], 30);
push(list[1], 45);
push(list[1], 35);
push(list[2], 100);
push(list[2], 80);
push(list[2], 70);
push(list[2], 60);
push(list[2], 10);
ListNode* ans = externalSort(list);
PrintList(ans);
return 0;
}
import java.util.*;
class ListNode {
int data;
ListNode next;
ListNode(int data)
{
this.data = data;
this.next = null;
}
}
class CompareNode implements Comparator<ListNode> {
@Override public int compare(ListNode a, ListNode b)
{
return Integer.compare(a.data, b.data);
}
}
public class GfG {
static ListNode createNode(int data)
{
return new ListNode(data);
}
static void push(ListNode[] head, int data, int index)
{
if (head[index] == null) {
head[index] = createNode(data);
}
else {
ListNode newNode = createNode(data);
newNode.next = head[index];
head[index] = newNode;
}
}
static void PrintList(ListNode head)
{
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
static ListNode mergeLists(List<ListNode> lists)
{
ListNode dummy = createNode(0);
ListNode tail = dummy;
PriorityQueue<ListNode> minHeap
= new PriorityQueue<>(new CompareNode());
for (ListNode list : lists) {
if (list != null) {
minHeap.offer(list);
}
}
while (!minHeap.isEmpty()) {
ListNode node = minHeap.poll();
tail.next = node;
tail = tail.next;
if (node.next != null) {
minHeap.offer(node.next);
}
}
return dummy.next;
}
static ListNode externalSort(ListNode[] list)
{
List<ListNode> lists = new ArrayList<>();
for (ListNode node : list) {
lists.add(node);
}
return mergeLists(lists);
}
public static void main(String[] args)
{
int n = 3;
ListNode[] list = new ListNode[n];
list[0] = null;
push(list, 50, 0);
push(list, 40, 0);
push(list, 30, 0);
list[1] = null;
push(list, 45, 1);
push(list, 35, 1);
list[2] = null;
push(list, 100, 2);
push(list, 80, 2);
push(list, 70, 2);
push(list, 60, 2);
push(list, 10, 2);
ListNode ans = externalSort(list);
PrintList(ans);
}
}
import heapq
class ListNode:
def __init__(self, data):
self.data = data
self.next = None
def push(head, data):
# Function to insert a new node at the beginning of a linked list
new_node = ListNode(data)
new_node.next = head
head = new_node
return head
def PrintList(head):
# Function to print the linked list
while head:
print(head.data, end=" ")
head = head.next
print()
def merge_lists(lists):
# Function to merge K sorted linked lists into a single sorted linked list
dummy = ListNode(0)
tail = dummy
# Use a min heap to keep track of the smallest nodes from each list
min_heap = []
for lst in lists:
if lst:
# Push the first node of each list into the min heap
heapq.heappush(min_heap, (lst.data, lst))
while min_heap:
# Pop the smallest node from the min heap
data, node = heapq.heappop(min_heap)
# Append the smallest node to the sorted linked list
tail.next = node
tail = tail.next
# If the popped node has a next node, push it into the min heap
if node.next:
heapq.heappush(min_heap, (node.next.data, node.next))
return dummy.next
def externalSort(list):
# Function to perform external sorting on an list of linked lists
sorted_list = merge_lists(list)
return sorted_list
if __name__ == "__main__":
N = 3 # Number of machines
list = [None] * N
# Create the linked lists for each machine
list[0] = None
list[0] = push(list[0], 50)
list[0] = push(list[0], 40)
list[0] = push(list[0], 30)
list[1] = None
list[1] = push(list[1], 45)
list[1] = push(list[1], 35)
list[2] = None
list[2] = push(list[2], 100)
list[2] = push(list[2], 80)
list[2] = push(list[2], 70)
list[2] = push(list[2], 60)
list[2] = push(list[2], 10)
# Sort all elements
ans = externalSort(list)
PrintList(ans)
using System;
using System.Collections.Generic;
public class ListNode {
public int data;
public ListNode next;
}
public class MinHeap {
private List<Tuple<ListNode, int> > heap;
public MinHeap()
{
heap = new List<Tuple<ListNode, int> >();
}
public void Enqueue(ListNode node, int value)
{
heap.Add(new Tuple<ListNode, int>(node, value));
HeapifyUp();
}
public ListNode Dequeue()
{
if (heap.Count == 0)
throw new InvalidOperationException(
"Heap is empty.");
var root = heap[0].Item1;
heap[0] = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
HeapifyDown();
return root;
}
public int Count => heap.Count;
private void HeapifyUp()
{
int index = heap.Count - 1;
while (index > 0) {
int parentIndex = (index - 1) / 2;
if (heap[index].Item2
>= heap[parentIndex].Item2)
break;
var temp = heap[index];
heap[index] = heap[parentIndex];
heap[parentIndex] = temp;
index = parentIndex;
}
}
private void HeapifyDown()
{
int index = 0;
while (index * 2 + 1 < heap.Count) {
int leftChildIndex = index * 2 + 1;
int rightChildIndex = leftChildIndex + 1;
int smallestChildIndex = leftChildIndex;
if (rightChildIndex < heap.Count
&& heap[rightChildIndex].Item2
< heap[leftChildIndex].Item2) {
smallestChildIndex = rightChildIndex;
}
if (heap[index].Item2
<= heap[smallestChildIndex].Item2)
break;
var temp = heap[index];
heap[index] = heap[smallestChildIndex];
heap[smallestChildIndex] = temp;
index = smallestChildIndex;
}
}
}
public class GfG {
public static ListNode CreateNode(int data)
{
return new ListNode{ data = data, next = null };
}
public static void Push(ref ListNode head, int data)
{
ListNode newNode = CreateNode(data);
newNode.next = head;
head = newNode;
}
public static void PrintList(ListNode head)
{
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
Console.WriteLine();
}
public static ListNode MergeLists(List<ListNode> lists)
{
ListNode dummy = CreateNode(0);
ListNode tail = dummy;
MinHeap minHeap = new MinHeap();
foreach(ListNode list in lists)
{
if (list != null)
minHeap.Enqueue(list, list.data);
}
while (minHeap.Count > 0) {
ListNode node = minHeap.Dequeue();
tail.next = node;
tail = tail.next;
if (node.next != null)
minHeap.Enqueue(node.next, node.next.data);
}
return dummy.next;
}
public static ListNode ExternalSort(ListNode[] list,
int N)
{
List<ListNode> lists = new List<ListNode>(list);
return MergeLists(lists);
}
public static void Main(string[] args)
{
int N = 3;
ListNode[] list = new ListNode[N];
list[0] = null;
Push(ref list[0], 50);
Push(ref list[0], 40);
Push(ref list[0], 30);
list[1] = null;
Push(ref list[1], 45);
Push(ref list[1], 35);
list[2] = null;
Push(ref list[2], 100);
Push(ref list[2], 80);
Push(ref list[2], 70);
Push(ref list[2], 60);
Push(ref list[2], 10);
ListNode ans = ExternalSort(list, N);
PrintList(ans);
}
}
class ListNode {
constructor(data) {
this.data = data;
this.next = null;
}
}
class PriorityQueue {
constructor(comparator) {
this.comparator = comparator || ((a, b) => a - b);
this.data = [];
}
get count() {
return this.data.length;
}
enqueue(item) {
this.data.push(item);
this.data.sort(this.comparator);
}
dequeue() {
if (this.count === 0) {
throw new Error("Priority queue is empty.");
}
return this.data.shift();
}
}
function createNode(data) {
return new ListNode(data);
}
function push(head, data) {
if (!head) {
return createNode(data);
} else {
const newNode = createNode(data);
newNode.next = head;
return newNode;
}
}
function printList(head) {
let current = head;
let result = [];
while (current) {
result.push(current.data);
current = current.next;
}
console.log(result.join(' '));
}
function mergeLists(lists) {
const dummy = createNode(0);
let tail = dummy;
const minHeap = new PriorityQueue((a, b) => a.data - b.data);
lists.forEach(list => {
if (list !== null) {
minHeap.enqueue(list);
}
});
while (minHeap.count > 0) {
const node = minHeap.dequeue();
tail.next = node;
tail = tail.next;
if (node.next !== null) {
minHeap.enqueue(node.next);
}
}
return dummy.next;
}
function externalSort(list, n) {
return mergeLists(list);
}
function main() {
const n = 3;
const list = new Array(n);
list[0] = null;
list[0] = push(list[0], 50);
list[0] = push(list[0], 40);
list[0] = push(list[0], 30);
list[1] = null;
list[1] = push(list[1], 45);
list[1] = push(list[1], 35);
list[2] = null;
list[2] = push(list[2], 100);
list[2] = push(list[2], 80);
list[2] = push(list[2], 70);
list[2] = push(list[2], 60);
list[2] = push(list[2], 10);
const ans = externalSort(list, n);
printList(ans);
}
main();
Output
10 30 35 40 45 50 60 70 80 100
Time Complexity: O(K log2n), where n is the numbers of array.
Auxiliary Space: O(K), where K is number of total elements in all array.
[Approach 2] - Using Merge of Merge Sort - Good for Equal-Sized
This problem is closely related to Merging K Sorted Arrays & Merge K sorted linked lists. In all cases, the goal is to efficiently merge multiple sorted sequences into a single sorted output. Here, instead of traditional arrays or linked lists, the numbers are distributed across different machines, making it a distributed computing variation of the same concept.