信息论霍夫曼编码c语言,霍夫曼编码C语言

编译成功

/* Note:Your choice is C IDE */

#include

#include

#define N 15

#define M 2*N-1

typedef struct

{float weight;

unsigned int parent,lchild,rchild;

}HTNode;

typedef struct

{

char data;

float weight;

char code[N];

}HTCode;

main()

{

int i,m,n,w[N+1];

float l=0.0;

HTNode ht[M+1];

HTCode hc[N+1];

Init (hc,&n);

HuffmanCoding (ht,hc,n);

for(i=1;i<=n;i++)

printf("\nThe code of '%c' is :%s",hc[i].data,hc[i].code);

for(i=1;i<=n;i++)

{l+=strlen (hc[i].code)*hc[i].weight;}

/*l=l/n;*/

printf("\n The average length of the Huffman coding is %f",l);

}

Init (HTCode hc[],int *n)

{

int i;

printf("\n input n=");

scanf("%d",&(*n));

fflush(stdin);

printf("\n input %d character \n",*n);

for(i=1;i<=*n;i++)

{printf("\n the %d character is:",i);

scanf("%c",&(hc[i].data));

fflush(stdin);

}

for(i=1;i<=*n;i++)

{printf("\n the %d character weight is:",i);

scanf("%f",&(hc[i].weight));}

}

HuffmanCoding (HTNode ht[],HTCode hc[],int n)

{

char cd[N];

int i,j,m,c,f,s1,s2,start;

m=2*n-1; /*2n-1个节点*/

for(i=1;i<=m;i++) /*初始化节点,1~n个原始节点有值*/

{

if(i<=n) ht[i].weight=hc[i].weight;

else ht[i].weight=0.0;

ht[i].parent=ht[i].lchild=ht[i].rchild=0;

}

for(i=n+1;i<=m;i++) /*构造二叉树*/

{

Select(ht,i-1,&s1,&s2); /*选择最小的两个概率节点,并且没有编码过的*/

ht[s1].parent=i;ht[s2].parent=i;

ht[i].lchild=s1;ht[i].rchild=s2;

ht[i].weight=ht[s1].weight+ht[s2].weight;

}

for(i=1;i<=m;i++)

{

printf("\n the %d charactor weight is %f:",i,ht[i].weight);

printf("\n the %d charactor lchild is %d:",i,ht[i].lchild);

printf("\n the %d charactor rchild is %d:",i,ht[i].rchild);

printf("\n the %d charactor parent is %d:",i,ht[i].parent);

}

for(i=0;i

cd[i]="";

cd[n-1]='\0'; /*编码初始化*/

for(i=1;i<=n;i++)

{

start=n-1;

for(c=i,f=ht[i].parent;f;f=ht[f].parent) /*遍历到父节点*/

if(ht[f].lchild==c)

cd[--start]='0';

else

cd[--start]='1';

strcpy(hc[i].code,&cd[start]);

}

}

Select(HTNode ht[],int k,int *s1,int *s2)

{

int i;

for(i=1;i<=k;i++)

{

if(ht[i].parent==0)

{*s1=i;

break;}

}

for(i=1;i<=k;i++)

if(ht[i].parent==0&&ht[i].weight

*s1=i;

for(i=1;i<=k;i++)

{if(ht[i].parent==0&&i!=*s1)

{*s2=i;

break;}

}

for(i=1;i<=k;i++)

if(ht[i].parent==0&&i!=*s1&&ht[i].weight

*s2=i;

printf("\n This is *s1:%d\n",*s1);

printf("\n This is *s2:%d\n",*s2);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值