Skip to content

Instantly share code, notes, and snippets.

@maheshmc2
Created January 31, 2011 19:34
Show Gist options
  • Save maheshmc2/804639 to your computer and use it in GitHub Desktop.
Save maheshmc2/804639 to your computer and use it in GitHub Desktop.
public class Element implements Comparable<Element>{
String val;
int count;
String code = null;
Element leftChild;
Element rightChild;
public Element(String v, int c){
this.val = v;
this.count = c;
this.leftChild = null;
this.rightChild = null;
}
public Element(Element l, Element r){
this.leftChild = l;
this.rightChild = r;
this.count = l.getCount() + r.getCount();
this.val = null;
}
public int getCount(){ return this.count; }
public void propogate(String code){
this.code = code;
if(leftChild != null)
leftChild.propogate(code+"0");
if(rightChild != null)
rightChild.propogate(code+"1");
}
@Override
public int compareTo(Element e){
if(this.getCount() > e.getCount())
return 1;
else if(this.getCount() == e.getCount())
return 0;
else
return -1;
}
@Override
public String toString(){
return "Value = "+val+" Frequency = "+count+" Code = "+code;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
int size = 7;
Element[] list = new Element[size];
ArrayList<Element> arr = new ArrayList<Element>();
for(int i=0 ; i<size ; ++i){
list[i] = new Element((i+1)+"", size-i);
arr.add(list[i]);
}
while(arr.size() > 1){
Collections.sort(arr);
Element temp1 = arr.remove(0);
Element temp2 = arr.remove(0);
arr.add(new Element(temp1, temp2));
}
Element temp = arr.get(0);
temp.propogate("");
for(int i=0 ; i<list.length ; ++i){
System.out.println(list[i]);
}
System.out.println("##.. End of Processing.. ");
}
}
Value = 1 Frequency = 7 Code = 10
Value = 2 Frequency = 6 Code = 00
Value = 3 Frequency = 5 Code = 111
Value = 4 Frequency = 4 Code = 110
Value = 5 Frequency = 3 Code = 010
Value = 6 Frequency = 2 Code = 0111
Value = 7 Frequency = 1 Code = 0110
##.. End of Processing..
@maheshmc2
Copy link
Author

Huffman Encoding...

@sau003
Copy link

sau003 commented Feb 1, 2011

sahii hai mahesh!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment