-
Notifications
You must be signed in to change notification settings - Fork 47
/
HuffmanCoding.cpp
68 lines (54 loc) Β· 1.34 KB
/
HuffmanCoding.cpp
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 min_heap_node {
char data;
unsigned freq;
min_heap_node *left, *right;
min_heap_node(char data, unsigned freq)
{
left = right = NULL;
this->data = data;
this->freq = freq;
}
};
struct compare {
bool operator()(min_heap_node* l, min_heap_node* r)
{
return (l->freq > r->freq);
}
};
void print_codes(struct min_heap_node* root, string str)
{
if (!root)
return;
if (root->data != '$')
cout << root->data << ": " << str << "\n";
print_codes(root->left, str + "0");
print_codes(root->right, str + "1");
}
void huff_code(char data[], int freq[], int size)
{
struct min_heap_node *left, *right, *top;
priority_queue<min_heap_node*, vector<min_heap_node*>, compare> min_heap;
for (int i = 0; i < size; ++i)
min_heap.push(new min_heap_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 min_heap_node('$', left->freq + right->freq);
top->left = left;
top->right = right;
min_heap.push(top);
}
print_codes(min_heap.top(), "");
}
int main()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
huff_code(arr, freq, size);
return 0;
}