MCPcopy Create free account
hub / github.com/PrajaktaSathe/Java / Huffman

Class Huffman

Programs/HuffmanCoding.java:21–77  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19
20// Implementing the huffman algorithm
21public class Huffman {
22 public static void printCode(HuffmanNode root, String s) {
23 if (root.left == null && root.right == null && Character.isLetter(root.c)) {
24
25 System.out.println(root.c + " | " + s);
26
27 return;
28 }
29 printCode(root.left, s + "0");
30 printCode(root.right, s + "1");
31 }
32
33 public static void main(String[] args) {
34
35 int n = 4;
36 char[] charArray = { 'A', 'B', 'C', 'D' };
37 int[] charfreq = { 5, 1, 6, 3 };
38
39 PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new ImplementComparator());
40
41 for (int i = 0; i < n; i++) {
42 HuffmanNode hn = new HuffmanNode();
43
44 hn.c = charArray[i];
45 hn.item = charfreq[i];
46
47 hn.left = null;
48 hn.right = null;
49
50 q.add(hn);
51 }
52
53 HuffmanNode root = null;
54
55 while (q.size() > 1) {
56
57 HuffmanNode x = q.peek();
58 q.poll();
59
60 HuffmanNode y = q.peek();
61 q.poll();
62
63 HuffmanNode f = new HuffmanNode();
64
65 f.item = x.item + y.item;
66 f.c = '-';
67 f.left = x;
68 f.right = y;
69 root = f;
70
71 q.add(f);
72 }
73 System.out.println(" Char | Huffman code ");
74 System.out.println("--------------------");
75 printCode(root, "");
76 }
77}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected