next up previous
Next: Example Up: CSE 2320: Algorithms and Previous: Prefix Codes

Greedy Algorithm for Huffman Code

Idea: Merge the two nodes (leaf or internal) into a new node until every leaf has been considered.

Use a priority queue Q to keep nodes ordered by frequency.

   Huffman(c)                        ; Analysis
      n = |c|                        ; Q is a binary heap
      Q = c                          ; O(n) BuildHeap
      for i = 1 to n-1               ; O(n)
         z = Allocate-Node()
         x = Extract-Min(Q)          ; O(lgn) O(n) times
         y = Extract-Min(Q)          ; O(lgn) O(n) times
         left(z) = x
         right(z) = y
         f(z) = f(x) + f(y)
         Insert(Q,z)                 ; O(lgn) O(n) times
      return Extract-Min(Q)          ; -----------------
                                     ; O(nlgn)



Copyright © 1998 The University of Texas at Arlington