|
Data Structures and Algorithms
with Object-Oriented Design Patterns in Python |
Merging two binomial queues is like doing binary addition.
For example, consider the addition of
and
:
| | | | | | | ||
| + | | | | | | ||
|
| | | | | | | |
In the next step,
we add the
from
and the
from
.
Combining the two
s we get a
which we carry
to the next column.
Since there are no
s left,
the result does not contain any.
The addition continues in a similar manner
until all the columns have been added up.
Program
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.

Program: BinomialQueue class merge method.
Each iteration of the main loop of the algorithm (lines 11-28)
computes the
``bit'' of the result--the
bit is a binomial tree of order i.
At most three terms need to be considered:
the carry from the preceding iteration and two
s,
one from each of the queues that are being merged.
The method fullAdder
computes the result required in each iteration.
Program
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
![]()

Program: BinomialQueue class fullAdder method.
Suppose the merge method of Program
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
binomial trees in the result.
Thus, the worst-case running time for the merge operation is
![]()