Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging sorted arrays [duplicate]

Tags:

algorithm

Possible Duplicates:
Merging two sorted lists
Algorithm for N-way merge

Given k sorted arrays each of length n, construct a single merged and sorted array.focus on running time and space complexity.

Source : Amazon interview question.
Any thoughts? thanks

like image 331
Josh Morrison Avatar asked Mar 21 '11 06:03

Josh Morrison


People also ask

Does merge sort work with duplicates?

To use merge sort to remove duplicates, you would ignore elements that are repeated in the merging process. This reply answered the question recusively. take a look at the instructions for Mergesort.

How do I merge two arrays without duplicates in C++?

Method 1: By traversing both the arrays to keep track of the current element in each arrays and finding the minimum value among the two and updating the output_array with the least value. Method 2: Concatenate the two arrays into one and then sorting the entire array. Method 3: Another approach is by using min-heaps.


1 Answers

Make a heap from the first element in each array. Pop the head element from the heap, insert it into the result array, and then take the next element from the array the head of the heap came from, and insert that into the heap. Repeat until you consume all of the arrays.

like image 196
Null Set Avatar answered Oct 17 '22 21:10

Null Set