-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHuffman_coding.c
68 lines (68 loc) · 1.96 KB
/
Huffman_coding.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
struct node
{
char data;
int freq;
node *left, *right;
node(char data, int freq)
{
left=NULL;
right=NULL;
this->data = data;
this->freq = freq;
}
};
struct compare
{
bool operator()(node* left, node* right)
{
return ((left->freq)>(right->freq));
}
};
void print(node* root, string str)
{
if(root==NULL)
return;
if (root->data != '-')
cout<<root->data << ": " <<str<< "\n";
print(root->left, str + "0");
print(root->right, str + "1");
}
void codes(char data[], int freq[], int n)
{
node *left, *right, *top;
priority_queue<node*, vector<node*>, compare> min_heap;
for (int i=0; i<n;i++)
min_heap.push(new node(data[i], freq[i]));
while (min_heap.size() != 1)
{
left = min_heap.top();
min_heap.pop();
right = min_heap.top();
min_heap.pop();
top = new node('-',(left->freq + right->freq));
top->left = left;
top->right = right;
min_heap.push(top);
}
cout<<"Required codes are:\n";
print(min_heap.top(), "");
}
int main()
{
char A[20];
int freq[20],n;
cout<<"Enter the number of characters:";
cin>>n;
cout<<"Enter the letters along with their frequencies:\n";
for(int i=0;i<n;i++)
{
cout<<i+1<<".Letter:";
cin>>A[i];
cout<<" Frequency:";
cin>>freq[i];
}
codes(A,freq,n);
return 0;
}