-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathHuffman.java
More file actions
76 lines (55 loc) · 1.47 KB
/
Huffman.java
File metadata and controls
76 lines (55 loc) · 1.47 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
// Huffman Coding Algorithm
import java.util.*; //importing all the classes from the "utility" at a time
class Node {
int element;
char c;
Node left;
Node right;
}
class ImplementComparator implements Comparator<Node> {
public int compare(Node x, Node y) {
return x.element - y.element;
}
}
// class implementing the Huffman Algorithm
public class Huffman {
public static void outCode(Node r, String s) {
if (r.left == null && r.right == null && Character.isLetter(r.c)) {
System.out.println(r.c + " | " + s);
return;
}
outCode(r.left, s + "0");
outCode(r.right, s + "1");
}
public static void main(String[] args) { // main method: the execution of the program starts from here
int n = 4;
char[] cArray = { 'A', 'B', 'C', 'D' };
int[] cf = { 5, 1, 6, 3 };
PriorityQueue<Node> k = new PriorityQueue<Node>(n, new ImplementComparator());
for (int i = 0; i < n; i++) {
Node t = new Node();
t.c = cArray[i];
t.element = cf[i];
t.left = null;
t.right = null;
k.add(t);
}
Node r = null;
while (k.size() > 1) {
Node x = k.peek();
k.poll();
Node y = k.peek();
k.poll();
Node f = new Node();
f.element = x.element + y.element;
f.c = '-';
f.left = x;
f.right = y;
r = f;
k.add(f);
}
System.out.println(" Char|Huffman code ");
System.out.println("--------------------");
outCode(r, "");
}
}