Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is iterative k-way merge O(nk^2)?

Tags:

algorithm

k-way merge is the algorithm that takes as input k sorted arrays, each of size n. It outputs a single sorted array of all the elements.

It does so by using the "merge" routine central to the merge sort algorithm to merge array 1 to array 2, and then array 3 to this merged array, and so on until all k arrays have merged.

I had thought that this algorithm is O(kn) because the algorithm traverses each of the k arrays (each of length n) once. Why is it O(nk^2)?

like image 995
dangerChihuahua007 Avatar asked Jun 14 '12 03:06

dangerChihuahua007


People also ask

What is K way merging in data structure?

In computer science, k-way merge algorithms or multiway merges are a specific type of sequence merge algorithms that specialize in taking in k sorted lists and merging them into a single sorted list. These merge algorithms generally refer to merge algorithms that take in a number of sorted lists greater than two.

What is iterative merge sort?

In iterative merge sort, we will divide the elements into equal halves using a recursive approach and then merge them back as a sorted array using the iterative approach.

What is 2 way merge?

two-way merge An algorithm that merges two ordered files into one single sorted file. It may be viewed as a generalization of sorting by insertion, and was proposed by John von Neumann in 1945. A Dictionary of Computing. "two-way merge ."


1 Answers

Because it doesn't traverse each of the k arrays once. The first array is traversed k-1 times, the first as merge(array-1,array-2), the second as merge(merge(array-1, array-2), array-3) ... and so on.

The result is k-1 merges with an average size of n*(k+1)/2 giving a complexity of O(n*(k^2-1)/2) which is O(nk^2).

The mistake you made was forgetting that the merges are done serially rather than in parallel, so the arrays are not all size n.

like image 133
Recurse Avatar answered Nov 08 '22 09:11

Recurse