现在的位置: 首页 > 综合 > 正文

合并两个二项堆的伪代码

2013年10月13日 ⁄ 综合 ⁄ 共 1862字 ⁄ 字号 评论关闭
BINOMIAL-LINK(y, z)子过程用于将以结点y为根的Bk-1树与以结点z为根的Bk-1树连接起来,
亦即,它使得z成为y的父结点,并且成为一颗Bk树的根。
BINOMIAL-LINK(y, z)子过程的伪代码如下:
BINOMIAL-LINK(y, z)
1  p[y]  z
2  sibling[y]  child[z]
3  child[z]  y
4  degree[z]  degree[z] + 1
 
BINOMIAL-HEAP-MERGE(H1, H2)子过程,用于将H1H2的根表合并成一个按度数的单调递增次序排列的链表。
BINOMIAL-HEAP-MERGE(H1, H2)子过程的伪代码如下:
BINOMIAL-HEAP-MERGE(H1, H2)

1  head Head[H1]

2  if head = NIL

3    then head ← Head[H2]

4      return head

5  else if Head[H2] = NIL

6    then return head

7  else

8    x ←Head[H1]

9    y ← Head[H2]

10   if degree[y]<degree[x]

11     then head y

12         y ← sibling[y]

13    else  x ← sibling[x]

14    curr ← head

15    while x NIL and y NIL

16      do if degree[y]<degree[x]

17        then   sibling [curr] ←y

18              y ← sibling[y]

19        else   sibling [curr] ←x

20              x ← sibling[x]

21        curr ←sibling [curr]

22    if x NIL

23      sibling [curr] ← x

24    else

25      sibling[curr] ← y

26    return head

 

最后合并两个堆的伪代码如下:

BINOMIAL-HEAP-UNION(H1, H2)

 1  H MAKE-BINOMIAL-HEAP()

 2  head[H] BINOMIAL-HEAP-MERGE(H1, H2)

 3  free the objects H1 and H2 but not the lists they point to

 4  if head[H] = NIL

 5     then return H

 6  prev-x NIL

 7  x head[H]

 8  next-x sibling[x]

 9  while next-x NIL

10      do if (degree[x] degree[next-x]) or

                (sibling[next-x] NIL and degree[sibling[next-x]] = degree[x])

11            then prev-x x                                Cases 1 or 2

12                 x next-x                                Cases 1 or 2

13            else if key[x] key[next-x]

14                    then sibling[x] sibling[next-x]          Case 3

15                         BINOMIAL-LINK(next-x, x)               Case 3

16                    else if prev-x = NIL                        Case 4

17                            then head[H] next-x              Case 4

18                            else sibling[prev-x] next-x       Case 4

19                         BINOMIAL-LINK(x, next-x)               Case 4

20                         x next-x                            Case 4

21         next-x sibling[x]

22  return H

 

抱歉!评论已关闭.