Sort numbers stored on different machines - GeeksforGeeks
Given N machines. 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.
Example: Machine M1 contains 3 numbers: {30, 40, 50} Machine M2 contains 2 numbers: {35, 45} Machine M3 contains 5 numbers: {10, 60, 70, 80, 100} Output: {10, 30, 35, 40, 45, 50, 60, 70, 80, 100} Representation of stream of numbers on each machine is considered as linked list. A Min Heap can be used to print all numbers in sorted order.
Following is the detailed process
1. Store the head pointers of the linked lists in a minHeap of size N where N is number of machines.
2. Extract the minimum item from the minHeap. Update the minHeap by replacing the head of the minHeap with the next number from the linked list or by replacing the head of the minHeap with the last number in the minHeap followed by decreasing the size of heap by 1.
3. Repeat the above step 2 until heap is not empty.
Read full article from Sort numbers stored on different machines - GeeksforGeeks
No comments:
Post a Comment