微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++霍夫曼编码Huffman Coding

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

霍夫曼编码(Huffman Coding)是一种编码方式,是一种用于无损数据压缩的熵编码(权编码)算法。1952年,David A. Huffman在麻省理工攻读博士时所发明的,并发表于《一种构建极小多余编码的方法》(A Method for the Construction of Minimum-Redundancy Codes)一文。
在计算机数据处理中,霍夫曼编码使用变长编码表对源符号(如文件中的一个字母) 进行编码,其中变长编码表是通过一种评估来源符号出现机率的方法得到的,出现机率高的字母使用较短的编码,反之出现机率低的则使用较长的编码,这便使编码 之后的字符串的平均长度、期望值降低,从而达到无损压缩数据的目的。( http://zh.wikipedia.org/wiki/Huffman%E7%B7%A8%E7%A2%BC)
#include<iostream>
 #include<string>
 #include<queue>
 using namespace std;
  
 class node{
     public:
        node(string con,float wht,node* left,node* right,string co ){
            content=con;
            weight=wht;
            leftchild=left;
            rightchild=right;
            code=co;
            }
        string content;
        float weight;
        node* leftchild;
        node* rightchild;
        string code;
     };
 
void insertion_sort(node** array,int low,int high){
    for(int i=low+1;i<high;i++){
        node* tem=array[i];
        int j=i-1;
        while(array[j]->weight>tem->weight&&j>=low){
            array[j+1]=array[j];
            j--;
            }
        array[j+1]=tem;
        }
    }
void create_huffman_tree(string* s,float* w,int n,node** array){
    for(int i=0;i<n;i++){
        array[i]=new node(s[i],w[i],NULL,"");
        }
    insertion_sort(array,n);
    //~ for(int i=0;i<n;i++){
        //~ cout<<array[i]->content<<"*";
        //~ }
    int p=0;
    while(p!=n-1){
        node* min_1=array[p];
        node* min_2=array[p+1];
        node* new_node=new node("",min_1->weight+min_2->weight,min_1,min_2,"");
        //cout<<new_node->weight<<endl;
        array[p+1]=new_node;
        p=p+1;
        insertion_sort(array,p,n);
        }
     
    }
     
void create_huffman_code(node* p){
    queue<node*> nq;
    nq.push(p);
    while(nq.size()!=0){
        node* cur=nq.front();
        nq.pop();
        node* l=cur->leftchild;
        if(l!=NULL){l->code=cur->code+"0"; nq.push(l);}
        node* r=cur->rightchild;
        if(r!=NULL){r->code=cur->code+"1"; nq.push(r);}
        if(l==NULL&&r==NULL){
            cout<<cur->content<<": "<<cur->code<<endl;
            }
        }
    }
 int main(int argc,char** argv){
     node* array[8];
     string s[8]={"a","b","c","d","e","f","g","h"};
     float w[8]={1,1,2,3,5,8,13,21};
     create_huffman_tree(s,w,array);
     create_huffman_code(array[7]);
     }

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐