Sort numbers stored on different machines
Last Updated :
17 Mar, 2025
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 mergeLists
function merges sorted linked lists using a min heap, repeatedly extracting the smallest element and inserting the next node. The externalSort
function converts the linked lists into a vector, calls mergeLists
to get the final sorted list, and prints it. Changing the comparison in CompareNode
allows sorting in descending order.
C++
#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;
}
Java
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);
}
}
Python
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)
C#
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);
}
}
JavaScript
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();
Output10 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.
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials
Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read