Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
afnan47
GitHub Repository: afnan47/sem7
Path: blob/main/DAA/2_Huffman_Coding.cpp
418 views
1
#include<bits/stdc++.h>
2
3
using namespace std;
4
5
struct MinHeapNode{
6
char data;
7
int freq;
8
MinHeapNode* left, *right;
9
MinHeapNode(char data, int freq){
10
left=right=nullptr;
11
this->data = data;
12
this->freq = freq;
13
}
14
};
15
16
17
void printCodes(struct MinHeapNode* root, string str){
18
if(root == nullptr){
19
return;
20
}
21
if(root->data != '$'){
22
cout << root->data << ": " << str << endl;
23
}
24
printCodes(root->left, str + "0");
25
printCodes(root->right, str + "1");
26
}
27
28
struct compare{
29
bool operator()(MinHeapNode* a, MinHeapNode* b){
30
return (a->freq > b->freq);
31
}
32
};
33
34
void HuffmanCode(char data[], int freq[], int size){
35
struct MinHeapNode *left, *right, *temp;
36
37
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;
38
39
for(int i = 0; i < size; i++){
40
minHeap.push(new MinHeapNode(data[i], freq[i]));
41
}
42
43
while(minHeap.size() != 1){
44
left = minHeap.top();
45
minHeap.pop();
46
right = minHeap.top();
47
minHeap.pop();
48
temp = new MinHeapNode('$', left->freq + right->freq);
49
temp->left = left;
50
temp->right = right;
51
minHeap.push(temp);
52
}
53
printCodes(minHeap.top(), "");
54
}
55
56
57
int main(){
58
char data[] = {'A', 'B', 'C', 'D'};
59
int freq[] = {23,12,34,10};
60
HuffmanCode(data, freq, 4);
61
return 0;
62
}
63
64
/*
65
Huffman Coding :
66
Time complexity: O(nlogn) where n is the number of unique characters.
67
If there are n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calls minHeapify(). So, overall complexity is O(nlogn).
68
*/
69