알고리즘 자바 실현-욕심 알고리즘-하 퍼 만 인 코딩

2440 단어 자바 알고리즘
하 퍼 만 인 코딩 자바 구현(욕심 알고리즘)
구체 적 인 문제 설명 및 C/C++참조 사이트 구현
http://blog.csdn.net/liufeng_king/article/details/8720896
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
 *     (    )
 * @author Lican
 *
 */
public  class Huffman implements Comparable {
	Bintree tree;
	float weight;
	String coding;
	public Huffman(Bintree tree,float weight){
		this.tree=tree;
		this.weight=weight;
	}
	@Override
	public int compareTo(Object x) {
		float w=((Huffman)x).weight;
		if(this.weight h){		
		while(h.size()>1){
			Collections.sort(h);
			Huffman h1=h.get(0);
			Huffman h2=h.get(1);
			float w=h1.weight+h2.weight;
			Bintree b1=h1.tree;
			Bintree b2=h2.tree;
			Bintree b=new Bintree(b1,b2,"");
			Huffman node=new Huffman(b,w);
			h.remove(0);
			h.remove(0);
			h.add(node);
		}
		return h.get(0);
	}
	/**
	 *       ,     0,     1
	 * @param node
	 * @param str
	 */
	public static void process(Bintree node,String str){  
        //      
        if(node.Left==null){  
            node.setCoding(str); 
            System.out.println(node.data+": "+node.coding);
            return;  
        }  
        //        "0"  
        process(node.Left,str+"0");  
        //        "1"  
        process(node.Right,str+"1");  
    } 
	public static void main(String[] args) {
		List h=new ArrayList();
		Bintree b1=new Bintree(null,null,"A");
		Huffman h1=new Huffman(b1,40);
		h.add(h1);
		Bintree b2=new Bintree(null,null,"B");
		Huffman h2=new Huffman(b2,8);
		h.add(h2);
		Bintree b3=new Bintree(null,null,"C");
		Huffman h3=new Huffman(b3,10);
		h.add(h3);
		Bintree b4=new Bintree(null,null,"D");
		Huffman h4=new Huffman(b4,30);
		h.add(h4);
		Bintree b5=new Bintree(null,null,"E");
		Huffman h5=new Huffman(b5,10);
		h.add(h5);
		Bintree b6=new Bintree(null,null,"F");
		Huffman h6=new Huffman(b6,2);
		h.add(h6);
		Huffman root=createHuffmanTree(h);
		process(root.tree,"");
	}
}
/**
A: 0
D: 10
F: 1100
B: 1101
C: 1110
E: 1111
*/

좋은 웹페이지 즐겨찾기