Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathHuffmanCoding.java
More file actions
Latest commit
113 lines (62 loc) · 1.5 KB
/
Copy pathHuffmanCoding.java
File metadata and controls
113 lines (62 loc) · 1.5 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
importjava.util.PriorityQueue;
importjava.util.Scanner;
importjava.util.Comparator;
classHuffmanNode {
intdata;
charc;
HuffmanNodeleft;
HuffmanNoderight;
}
classMyComparatorimplementsComparator<HuffmanNode> {
publicintcompare(HuffmanNodex, HuffmanNodey)
{
returnx.data - y.data;
}
}
publicclassHuffman {
publicstaticvoidprintCode(HuffmanNoderoot, Strings)
{
if (root.left
== null
&& root.right
== null
&& Character.isLetter(root.c)) {
System.out.println(root.c + ":" + s);
return;
}
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
publicstaticvoidmain(String[] args)
{
Scanners = newScanner(System.in);
intn = 6;
char[] charArray = { 'a', 'b', 'c', 'd', 'e', 'f' };
int[] charfreq = { 5, 9, 12, 13, 16, 45 };
PriorityQueue<HuffmanNode> q
= newPriorityQueue<HuffmanNode>(n, newMyComparator());
for (inti = 0; i < n; i++) {
HuffmanNodehn = newHuffmanNode();
hn.c = charArray[i];
hn.data = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
}
HuffmanNoderoot = null;
while (q.size() > 1) {
HuffmanNodex = q.peek();
q.poll();
HuffmanNodey = q.peek();
q.poll();
HuffmanNodef = newHuffmanNode();
f.data = x.data + y.data;
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
}
printCode(root, "");
}
}