Huffman coding algoritnm
Huffman coding algorithm:-
Huffman coding. Huffman Algorithm was developed by David Huffman in 1951. This is a technique which is used in a data compression or it can be said that it is a coding technique which is used for encoding data.
Huffman is widely used in all the mainstream compression formats that you might encounter - from GZIP, PKZIP (winzip etc) and BZIP2, to image formats such as JPEG and PNG.
algorithm:-
Huffman(c)
{
n = |c| //where mod of c is set of character
make a min heap 'Q' with c [O(n)]
for i in range n-1
// allocated a new node z
z.left = x = extract - min(Q)
z.rigth=y= extract - min(Q)
z.freg = x.freg + y.freg
Insert(Q,z)
return extract - min(Q)
}
Let see java program using Huffman coding algorithm:-
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Comparator;
//createting node
class HuffmanNode{
int data;
char c;
HuffmanNode left;
HuffmanNode right;
}
//compare to node
class MyComparator implements Comparator<HuffmanNode>{
public int compare(HuffmanNode x, HuffmanNode y){
return x.data - y.data;
}
}
class Huffman{
public static void printCode(HuffmanNode root , String s){
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");
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the totle character:");
int n = sc.nextInt();
System.out.println("Enter the Characters");
String str = sc.next();
char[] charArray = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
charArray[i] = str.charAt(i);
}
System.out.println("Enter the frequency");
int[] charfreq = new int[n];
for(int i=0; i<n; i++){
charfreq[i] = sc.nextInt();
}
PriorityQueue<HuffmanNode> q = new PriorityQueue<HuffmanNode>(n, new MyComparator());
for(int i=0; i<n; i++){
HuffmanNode hn = new HuffmanNode();
hn.c = charArray[i];
hn.data = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
}
HuffmanNode root = null;
while(q.size() > 1){
HuffmanNode x = q.peek();
q.poll();
HuffmanNode y = q.peek();
q.poll();
HuffmanNode f = new HuffmanNode();
f.data = x.data+y.data;
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
}
printCode(root, "");
}
}
Comments
Post a Comment