Skip to content

Commit 50e8a28

Browse files
committed
Added the implementation of Huffman coding in cpp
1 parent 0a0e1c5 commit 50e8a28

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <queue>
4+
#include <vector>
5+
#include <map>
6+
7+
using namespace std;
8+
9+
struct MinHeapNode
10+
{
11+
char data;
12+
unsigned freq;
13+
MinHeapNode *left, *right;
14+
15+
MinHeapNode(char data, unsigned freq)
16+
{
17+
left = right = nullptr;
18+
this->data = data;
19+
this->freq = freq;
20+
}
21+
};
22+
23+
struct compare
24+
{
25+
bool operator()(MinHeapNode *l, MinHeapNode *r)
26+
{
27+
return (l->freq > r->freq);
28+
}
29+
};
30+
31+
void printCodes(struct MinHeapNode *root, string str)
32+
{
33+
if (!root)
34+
return;
35+
36+
if (root->data != '$')
37+
cout << root->data << ": " << str << "\n";
38+
39+
printCodes(root->left, str + "0");
40+
printCodes(root->right, str + "1");
41+
}
42+
43+
void HuffmanCodes(string text)
44+
{
45+
map<char, unsigned> freq;
46+
for (char c : text)
47+
{
48+
freq[c]++;
49+
}
50+
51+
priority_queue<MinHeapNode *, vector<MinHeapNode *>, compare> minHeap;
52+
53+
for (auto pair : freq)
54+
{
55+
minHeap.push(new MinHeapNode(pair.first, pair.second));
56+
}
57+
58+
MinHeapNode *left, *right, *top;
59+
60+
while (minHeap.size() != 1)
61+
{
62+
left = minHeap.top();
63+
minHeap.pop();
64+
65+
right = minHeap.top();
66+
minHeap.pop();
67+
68+
top = new MinHeapNode('$', left->freq + right->freq);
69+
top->left = left;
70+
top->right = right;
71+
72+
minHeap.push(top);
73+
}
74+
75+
cout << "Huffman Codes for the text:\n";
76+
printCodes(minHeap.top(), "");
77+
}
78+
79+
int main()
80+
{
81+
string str = "huffman coding is a greedy algorithm";
82+
HuffmanCodes(str);
83+
return 0;
84+
}

0 commit comments

Comments
 (0)