Experiment-5 AIM:-To Implement Huffman Encoding Introduction
Experiment-5 AIM:-To Implement Huffman Encoding Introduction
Experiment-5 AIM:-To Implement Huffman Encoding Introduction
Introduction:-
Using the Huffman Coding technique, we can compress the string to a smaller size.
Huffman coding first creates a tree using the frequencies of the character and then generates code for each
character.
Once the data is encoded, it has to be decoded. Decoding is done using the same tree.
Huffman Coding prevents any ambiguity in the decoding process using the concept of prefix code ie. a
code associated with a character should not be present in the prefix of any other code.
Algorithm:-
create a newNode
calculate the sum of these two minimum values and assign it to the value of newNode
return rootNode
Analysis:-
The time complexity for encoding each unique character based on its frequency is O(nlog n).
Extracting minimum frequency from the priority queue takes place 2*(n-1) times and its complexity is
O(log n). Thus the overall complexity is O(nlog n).
Source Code:-
package exp6;
import java.util.PriorityQueue;
import java.util.Comparator;
class HuffmanNode {
int item;
char c;
HuffmanNode left;
HuffmanNode right;
return;
printCode(root.left, s + "0");
printCode(root.right, s + "1");
}
public static void main(String[] args) {
int n = 4;
int[] charfreq = { 5, 1, 6, 3 };
hn.c = charArray[i];
hn.item = charfreq[i];
hn.left = null;
hn.right = null;
q.add(hn);
HuffmanNode x = q.peek();
q.poll();
HuffmanNode y = q.peek();
q.poll();
f.c = '-';
f.left = x;
f.right = y;
root = f;
q.add(f);
System.out.println("--------------------");
printCode(root, "");
Output:-