From d9a6427cbf215ec85ad3267b8e2d37c96903231c Mon Sep 17 00:00:00 2001 From: Avinav Roy <79049223+Avi-Ro@users.noreply.github.com> Date: Tue, 18 Oct 2022 12:20:45 +0530 Subject: [PATCH] huffman.cpp Initial --- huffman.cpp | 111 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) create mode 100644 huffman.cpp diff --git a/huffman.cpp b/huffman.cpp new file mode 100644 index 0000000..5810045 --- /dev/null +++ b/huffman.cpp @@ -0,0 +1,111 @@ +#include +#include +using namespace std; + +struct Node +{ + int freq; + char ch; + Node* left,*right; + + Node(int f, char c, Node* l=NULL, Node* r=NULL) + { + freq=f; + ch=c; + left=l; + right=r; + } +}; + +struct compare +{ + bool operator()(Node* l , Node* r) + { + return l->freq > r->freq; + } +}; + + +void printCodes(Node* root, string str="") +{ + if(root->ch != '$') + { + cout<ch<<" "<left, str+"0"); + printCodes(root->right, str+"1"); +} + +void printHCodes(char arr[], int freq[], int n) +{ + priority_queue , compare> h; + + for(int i=0; i 1) + { + Node* l = h.top(); + + h.pop(); + + Node* r = h.top(); + + h.pop(); + + Node* node = new Node(l->freq+r->freq,'$',l,r); + + h.push(node); + } + + printCodes(h.top()); +} + +/*struct compare +{ + + bool operator()(Node* l , Node* r) + { + return l->freq > r->freq; + } +};*/ + + + +int main() +{ + int n; + + cout<<"Enter the number of distinguished characters : "<>n; + + char arr[n]; + int freq[n]; + + for(int i=0;i>arr[i]; + + cout<<"Frequncy "<<(i+1)<<" : "; + cin>>freq[i]; + } + + cout<<"CHARACTERS AND THEIR FREQUENCIES : "<