Skip to content

Commit 98431e2

Browse files
authored
feat: add Huffman Coding greedy algorithm implementation
1 parent 9aa2544 commit 98431e2

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package com.thealgorithms.greedyalgorithms;
2+
3+
import java.util.PriorityQueue;
4+
5+
/**
6+
* Huffman Coding Algorithm
7+
* Greedy algorithm used for optimal prefix codes.
8+
*/
9+
public class HuffmanCoding {
10+
11+
static class Node implements Comparable<Node> {
12+
char character;
13+
int frequency;
14+
Node left;
15+
Node right;
16+
17+
Node(char character, int frequency) {
18+
this.character = character;
19+
this.frequency = frequency;
20+
}
21+
22+
public int compareTo(Node other) {
23+
return this.frequency - other.frequency;
24+
}
25+
}
26+
27+
public static Node buildHuffmanTree(char[] chars, int[] freq) {
28+
PriorityQueue<Node> pq = new PriorityQueue<>();
29+
30+
for (int i = 0; i < chars.length; i++) {
31+
pq.add(new Node(chars[i], freq[i]));
32+
}
33+
34+
while (pq.size() > 1) {
35+
Node left = pq.poll();
36+
Node right = pq.poll();
37+
38+
Node parent = new Node('\0', left.frequency + right.frequency);
39+
parent.left = left;
40+
parent.right = right;
41+
42+
pq.add(parent);
43+
}
44+
45+
return pq.poll();
46+
}
47+
}

0 commit comments

Comments
 (0)