In computer science and information theory, a Huffman code is a particular type of optimal prefix code that is commonly used for lossless data compression. The process of finding and/or using such a code proceeds by means of Huffman coding, an algorithm developed by David A. Huffman while he was a Ph.D. student at MIT
C Code:
int adj[20][20];
main()
{
int n,i;
printf("Enter total number of frequencies");
scanf("%d",&n);
int a[100];
printf("Enter the frequecy");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int result[100][100];
int fy[100];
int node[8*n];
for(i=0;i<8*n;i++)
{
node[i]=i;
}
int l=n;int j;
int lm=0;
while(1)
{
for(i=lm;i<l;i++)
{
for(j=i+1;j<l;j++)
{
if(a[i]>a[j])//make this from bubble to merge or quick sort to run in O(nlogn)
{
int t=a[i];
int res=node[i];
a[i]=a[j];
node[i]=node[j];
a[j]=t;
node[j]=res;
}
}
}
int ssum=a[lm]+a[lm+1];
a[l]=ssum;
adj[node[lm]][node[l]]=1;
adj[node[lm+1]][node[l]]=2;
l++;
lm+=2;
if(lm==l-1)break;
}
for(i=0;i<n;i++)
{
{
int t=0;
int k=0;
int y=i;
int gg=0;
for(k=0;k<20;k++)
{
if(adj[y][k]!=0)
{
result[i][gg]=adj[y][k]-1;
gg++;
y=k;k=0;
}
}
fy[i]=gg;
}
}
int ri;
for(ri=0;ri<n;ri++)
{for(i=0;i<8*n;i++)
{
if(node[i]==ri)break;
}
printf("%d\t",a[i],fy[i]-1);
for(j=fy[ri]-1;j>=0;j--)
{
printf("%d",result[ri][j]);
}
printf("\n");
}
}
C Code:
int adj[20][20];
main()
{
int n,i;
printf("Enter total number of frequencies");
scanf("%d",&n);
int a[100];
printf("Enter the frequecy");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
int result[100][100];
int fy[100];
int node[8*n];
for(i=0;i<8*n;i++)
{
node[i]=i;
}
int l=n;int j;
int lm=0;
while(1)
{
for(i=lm;i<l;i++)
{
for(j=i+1;j<l;j++)
{
if(a[i]>a[j])//make this from bubble to merge or quick sort to run in O(nlogn)
{
int t=a[i];
int res=node[i];
a[i]=a[j];
node[i]=node[j];
a[j]=t;
node[j]=res;
}
}
}
int ssum=a[lm]+a[lm+1];
a[l]=ssum;
adj[node[lm]][node[l]]=1;
adj[node[lm+1]][node[l]]=2;
l++;
lm+=2;
if(lm==l-1)break;
}
for(i=0;i<n;i++)
{
{
int t=0;
int k=0;
int y=i;
int gg=0;
for(k=0;k<20;k++)
{
if(adj[y][k]!=0)
{
result[i][gg]=adj[y][k]-1;
gg++;
y=k;k=0;
}
}
fy[i]=gg;
}
}
int ri;
for(ri=0;ri<n;ri++)
{for(i=0;i<8*n;i++)
{
if(node[i]==ri)break;
}
printf("%d\t",a[i],fy[i]-1);
for(j=fy[ri]-1;j>=0;j--)
{
printf("%d",result[ri][j]);
}
printf("\n");
}
}
Time Complexity:O(nlog(n))