-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffman.java
More file actions
53 lines (47 loc) · 1.31 KB
/
Copy pathhuffman.java
File metadata and controls
53 lines (47 loc) · 1.31 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
import java.util.*;
public class huffman{
public static void main(String[] args){
char[] chArr = {'a','b','c','d','e','f','g','h'};
int[] freq = {10,20,30,5,8,16,40,2};
PriorityQueue<Pair> pq = new PriorityQueue<>();
for(int i = 0; i<freq.length; i++){
pq.offer(new Pair(chArr[i], freq[i]));
}
Pair root = null;
while(pq.peek()!=null){
Pair left = pq.poll();
Pair right = null;
if(pq.peek()!=null){
right = pq.poll();
root = new Pair('-', left.freq + right.freq);
pq.offer(root);
root.left = left;
root.right = right;
}else{
root = left;
break;
}
}
check(root);
}
public static void check(Pair root){
if(root == null) return;
System.out.println("ch >> "+ root.ch + " ::: freq >> " + root.freq);
check(root.left);
check(root.right);
}
}
class Pair implements Comparable<Pair>{
char ch;
int freq;
Pair right = null;
Pair left = null;
public Pair(char ch, int freq){
this.ch = ch;
this.freq = freq;
}
@Override
public int compareTo(Pair p){
return this.freq - p.freq;
}
}