views:

439

answers:

4
+1  A: 

From your description, it does sound like your process is indeed O(N log K). It also will work, so you can use it.

I personally would use the first version with a priority queue, since I suspect it will be faster. It's not faster in the coarse big-O sense, but I think if you actually work out the number of comparisons and stores taken by both, the second version will take several times more work.

Sean Owen
+1  A: 

This is O(2*log(K)*N) this is O(N*log(K)) and you can't have worst complexity because you only 2N times add to priority queue in O(log(K)).

Or you can push all elements into vector in O(2N). And sort it in O(2n*log(2n)). Then you have O(2N+2N*Log(2N)), this is O(N*LOG(N)), exacly your K = N;

Svisstack
Generally speaking, I only wanted to know if I'm right in my analysis, without taking the constants before `N log K` in account. Probably, if this would be a bottleneck place in my code, I would use the priority queue algorithm.
Kotti
A: 

It runs indeed in O(N*log K), but don't forget, that O(N*log K) is a subset of O(N*K). I.e. your friend is not wrong either.

phimuemue
Looks like a brilliant way to save our friendship :))
Kotti
+1  A: 

If you have a small number of lists to merge, this pairwise scheme is likely to be faster than a priority queue method because you have extremely few operations per merge: basically just one compare and two pointer reassignments per item (to shift into a new singly-linked list). As you've shown, it is O(N log K) (log K steps handling N items each).

But the best priority queue algorithms are, I believe, O(sqrt(log K)) or O(log log U) for insert and remove (where U is the number of possible different priorities)--if you can prioritize with a value instead of having to use a compare--so if you are merging items that can be given e.g. integer priorities, and K is large, then you're better off with a priority queue.

Rex Kerr
I actually think it's worth profiling. This theoretical analysis may sometimes benefit, but generally I'll now try to determine after what K does my approach begin to lack comparing to priority queue approach. Thanks for your answer.
Kotti