Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

Merging Binomial Queues

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

tex2html_wrap_inline65757 tex2html_wrap_inline65893 tex2html_wrap_inline62795 tex2html_wrap_inline65751 tex2html_wrap_inline65749 tex2html_wrap_inline66043
+ tex2html_wrap_inline65893 tex2html_wrap_inline62795 tex2html_wrap_inline65751 tex2html_wrap_inline62795 tex2html_wrap_inline66069

tex2html_wrap_inline66071 tex2html_wrap_inline62795 tex2html_wrap_inline62795 tex2html_wrap_inline66077 tex2html_wrap_inline62795 tex2html_wrap_inline65749 tex2html_wrap_inline66083

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

In the next step, we add the tex2html_wrap_inline65751 from tex2html_wrap_inline66043 and the tex2html_wrap_inline65751 from tex2html_wrap_inline66069. Combining the two tex2html_wrap_inline65751s we get a tex2html_wrap_inline66077 which we carry  to the next column. Since there are no tex2html_wrap_inline65751s 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. The Merge method of the BinomialQueue class takes a BinomialQueue and adds its subtrees to this binomial queue.

   program26946
Program: BinomialQueue class Merge method.

Each iteration of the main loop of the algorithm (lines 15-41) computes the tex2html_wrap_inline57621 ``bit'' of the result--the tex2html_wrap_inline57621 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_inline65991s, one from each of the queues that are being merged.

Two methods, Sum and Carry, compute the result required in each iteration. Program gif defines both Sum and Carry. Notice that the Sum method simply selects and returns one of its arguments. Therefore, the running time for Sum is clearly O(1).

   program26964
Program: BinomialQueue class Sum and Carry methods.

In the worst case, the Carry method calls the Add method to combine two BinomialTrees into one. Therefore, the worst-case running time for Carry is

displaymath66113

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_inline66199 binomial trees in the result. Thus, the worst-case running time for the Merge operation is

displaymath66114


next up previous contents index

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