The BOTTOM LINE Quote Of The Day

The BOTTOM LINE Quote Of The Day

Don't Ever Tell GOD How BIG Your Problems are.
Just Tell Your Problems How BIG your GOD is ;)

Saturday, February 12, 2011

Huffman Tree Algorithm (Simple)


#include<conio.h>
#include <stdio.h>
#define max 0
#define mxbits 20

struct ele
{
  int posn;
  int info;
  int code[mxbits];
  int lft;
  int rgt;
}ar[max],tr[max],item,item1,tmp1,tmp2,tmp3;

int noe,i,j,ptr,par,ind,left,right;

void ins_heap(int n,struct ele item)
{
 tr[n] = item;
 if(n != 1)
 {
 ptr = n;
 par = ptr/2;
 while(ptr>1 && tr[par].info > tr[ptr].info)
 {
  item = tr[par];
  tr[par] = tr[ptr];
  tr[ptr] = item;
  ptr = par;
  par = ptr/2;
 }
 }
}

void inp_dat()
{
 do
 {
 printf("\n\n Enter the no. of elements : ");
 scanf("%d",&noe);
 }while(noe<=0 || noe>=max/2);
 printf("\n\n Enter the frequencies '%d' elements : ",noe);
 for(i=1;i<=noe;i++)
  {
  scanf("%d",&ar[i].info);
  ar[i].posn = i;
  ar[i].lft = 0;
  ar[i].rgt = 0;
  ins_heap(i,ar[i]);
  }
}


struct ele del_heap(int end)
{
 item1 = tr[1];
 tr[1] = tr[end];
 par = 1; left = 2; right = 3;
 ind = 0;
 while(par < end && ind == 0)
 {
  if(tr[left].info < tr[par].info && tr[left].info < tr[right].info && left<end)
  {
  item = tr[left];
  tr[left] = tr[par];
  tr[par] = item;
  par = left;
  }
  else if(tr[right].info < tr[par].info && tr[left].info > tr[right].info  && right<end)
  {
  item = tr[right];
  tr[right] = tr[par];
  tr[par] = item;
  par = right;
  }
  else
   ind = 1;
  left = 2*par;
  right = 2*par+1;
 }
 return item1;
}

void hfmn_tree()
{
 i = noe;
 j = i+1;
 while(i>1)
 {
  tmp1 = del_heap(i);
  tmp2 = del_heap(--i);
  tmp3.info = tmp1.info + tmp2.info;
  tmp3.posn = j;
  tmp3.lft = tmp1.posn;
  tmp3.rgt = tmp2.posn;
  ar[j] = tmp3;
  ins_heap(i,tmp3);
  j++;
 }
 ar[j-1].posn = 1;
 i = j-1;
 while(i > noe)
 {
  ar[ar[i].lft].posn = 2*ar[i].posn;
  ar[ar[i].rgt].posn = 2*ar[i].posn+1;
  i--;
 }
}

void codes()
{
  int k;
  char ch;
  printf("\n The Codes for every input is : ");
  for(i=1;i<=noe;i++)
  {
   k = 0;
   ch = 64+i;
   printf(" \n For %c : %d. ",ch,ar[i].info);
   while(ar[i].posn > 1)
   {
   ar[i].code[k] = ar[i].posn % 2;
   ar[i].posn /= 2;
   k++;
   }
   for(j=k-1;j>=0;j--)
    printf("%d",ar[i].code[j]);
  }
}

void main()
{
clrscr();
inp_dat();
hfmn_tree();
codes();
getch();
}

No comments:

Post a Comment