diff --git a/Java/huffmanEncoder.java b/Java/huffmanEncoder.java new file mode 100644 index 0000000..a54d22a --- /dev/null +++ b/Java/huffmanEncoder.java @@ -0,0 +1,65 @@ +import java.util.Comparator; +import java.util.PriorityQueue; + +public class huffmanAlgo { + + static class Node { + int data; + char ch; + Node left; + Node right; + + public Node(int data) { + this.data = data; + } + + public Node(int data, char ch) { + this.data = data; + this.ch = ch; + } + } + + public static void printcode(Node n){ + printcode(n,""); + } + public static void printcode(Node n, String str) { //printing the encoded huffman code + if (n.left == null && n.right == null)//always only the leaf node will have a character stored + { + System.out.println(n.ch + ":\t" + str); + return; + } + printcode(n.left, str + "0"); + //recursing ustil reaching the leaf + printcode(n.right, str + "1"); + } + static class comp implements Comparator { + public int compare(Node a, Node b) { + return a.data - b.data; + } + } + public static void main(String[] args) { + char[] arr = { 'h', 'e', 't', 'r', 'p', 'a' ,'l'}; + int[] freq = {1,2,5,8,11,20,21}; + //taking priorly sorted elements with their frequencies + + PriorityQueue q= new PriorityQueue<>(freq.length,new comp()); + int i = 0; + while(i