Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Merging Binomial Queues

Merging two binomial queues is like doing binary addition. For example, consider the addition of tex2html_wrap_inline66267 and tex2html_wrap_inline66293:

tex2html_wrap_inline65981 tex2html_wrap_inline66117 tex2html_wrap_inline63013 tex2html_wrap_inline65975 tex2html_wrap_inline65973 tex2html_wrap_inline66267
+ tex2html_wrap_inline66117 tex2html_wrap_inline63013 tex2html_wrap_inline65975 tex2html_wrap_inline63013 tex2html_wrap_inline66293

tex2html_wrap_inline66295 tex2html_wrap_inline63013 tex2html_wrap_inline63013 tex2html_wrap_inline66301 tex2html_wrap_inline63013 tex2html_wrap_inline65973 tex2html_wrap_inline66307

The usual algorithm for addition begins with the least-significant ``bit.'' Since tex2html_wrap_inline66267 contains a tex2html_wrap_inline65973 tree and tex2html_wrap_inline66293 does not, the result is simply the tex2html_wrap_inline65973 tree from tex2html_wrap_inline66267.

In the next step, we add the tex2html_wrap_inline65975 from tex2html_wrap_inline66267 and the tex2html_wrap_inline65975 from tex2html_wrap_inline66293. Combining the two tex2html_wrap_inline65975s we get a tex2html_wrap_inline66301 which we carry  to the next column. Since there are no tex2html_wrap_inline65975s left, the result does not contain any. The addition continues in a similar manner until all the columns have been added up.

Program gif gives an implementation of this addition algorithm. In addition to self, the merge method of the BinomialQueue class takes a BinomialQueue and adds its subtrees to the binomial queue self.

   program27007
Program: BinomialQueue class merge method.

Each iteration of the main loop of the algorithm (lines 11-28) computes the tex2html_wrap_inline57847 ``bit'' of the result--the tex2html_wrap_inline57847 bit is a binomial tree of order i. At most three terms need to be considered: the carry from the preceding iteration and two tex2html_wrap_inline66215s, one from each of the queues that are being merged.

The method fullAdder computes the result required in each iteration. Program gif defines fullAdder method. In the worst case, the fullAdder method calls the add method to combine two BinomialTrees into one. Therefore, the worst-case running time for fullAdder is

displaymath66337

   program27026
Program: BinomialQueue class fullAdder method.

Suppose the merge method of Program gif is used to combine a binomial queue with n items with another that contains m items. Since the resulting priority queue contains n+m items, there are at most tex2html_wrap_inline66421 binomial trees in the result. Thus, the worst-case running time for the merge operation is

displaymath66338


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.