-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanCoding.java
More file actions
74 lines (63 loc) · 1.22 KB
/
HuffmanCoding.java
File metadata and controls
74 lines (63 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.util.Comparator;
import java.util.PriorityQueue;
class Node
{
char data;
int freq;
Node left, right;
}
class MyComparator implements Comparator<Node>
{
public int compare(Node x, Node y)
{
return x.freq - y.freq;
}
}
class HuffmanCoding
{
public static void printCode(Node root, String s)
{
if (root.left == null && root.right == null && Character.isLetter(root.data))
{
System.out.println(root.data + ":" + s);
return;
}
if (root.left != null)
{
printCode(root.left, s + "0");
}
if (root.right != null)
{
printCode(root.right, s + "1");
}
}
public static void main(String[] args)
{
int n = 7;
char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
int[] charfreq = {5, 10, 1, 25, 16, 61, 23};
PriorityQueue<Node> q = new PriorityQueue<>(n, new MyComparator());
for (int i = 0; i < n; i++)
{
Node hn = new Node();
hn.data = charArray[i];
hn.freq = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
}
while (q.size() > 1)
{
Node x = q.poll();
Node y = q.poll();
Node f = new Node();
f.freq = x.freq + y.freq;
f.data = '-';
f.left = x;
f.right = y;
q.add(f);
}
Node root = q.poll();
printCode(root, "");
}
}