-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman_Coding.java
100 lines (79 loc) · 1.96 KB
/
Huffman_Coding.java
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
/**
*
* @author pulkit4tech
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Comparator;
import java.util.PriorityQueue;
// Huffman Coding for lossless data compression
// Greedy Algorithm
class Huffman_Coding implements Runnable {
BufferedReader c;
PrintWriter pout;
// static long mod = 1000000007;
public void run() {
try {
c = new BufferedReader(new InputStreamReader(System.in));
pout = new PrintWriter(System.out, true);
solve();
pout.close();
} catch (Exception e) {
pout.close();
e.printStackTrace();
System.exit(1);
}
}
public static void main(String[] args) throws Exception {
new Thread(new Huffman_Coding()).start();
}
void solve() throws Exception {
Huffman();
}
void Huffman() {
char arr[] = { 'p', 'u', 'l', 'k', 'i', 't' };
long freq[] = { 1, 1, 12, 13, 16, 45 };
int size = arr.length;
HuffmanCodes(arr, freq, size);
}
class MinHeapNode {
char data;
long freq;
MinHeapNode left, right;
public MinHeapNode(char data, long freq) {
this.data = data;
this.freq = freq;
}
}
void HuffmanCodes(char data[], long freq[], int size) {
MinHeapNode left, right, top;
PriorityQueue<MinHeapNode> pq = new PriorityQueue<>(new Comparator<MinHeapNode>() {
@Override
public int compare(MinHeapNode o1, MinHeapNode o2) {
// TODO Auto-generated method stub
return Long.compare(o1.freq, o2.freq);
}
});
for (int i = 0; i < size; i++) {
pq.add(new MinHeapNode(data[i], freq[i]));
}
while (pq.size() != 1) {
left = pq.poll();
right = pq.poll();
top = new MinHeapNode('$', left.freq + right.freq);
top.left = left;
top.right = right;
pq.add(top);
}
printCodes(pq.peek(), "");
}
void printCodes(MinHeapNode root, String str) {
if (root == null)
return;
if (root.data != '$')
pout.println(root.data + ":" + str);
printCodes(root.left, str + "0");
printCodes(root.right, str + "1");
}
}