{"id":25081,"date":"2017-10-15T14:11:55","date_gmt":"2017-10-15T08:41:55","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=25081"},"modified":"2017-10-15T14:11:55","modified_gmt":"2017-10-15T08:41:55","slug":"efficient-huffman-coding-sorted-input","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/efficient-huffman-coding-sorted-input\/","title":{"rendered":"Efficient Huffman Coding for Sorted Input"},"content":{"rendered":"<p>We recommend to read following post as a prerequisite for this.<\/p>\n<p>Huffman Coding<\/p>\n<p>Time complexity of the algorithm discussed in above post is O(nLogn). <span id=\"more-26954\"><\/span>If we know that the given array is sorted (by non-decreasing order of frequency), we can generate Huffman codes in O(n) time. Following is a O(n) algorithm for sorted input.<\/p>\n<p><strong>1.<\/strong> Create two empty queues.<\/p>\n<p><strong>2.<\/strong> Create a leaf node for each unique character and Enqueue it to the first queue in non-decreasing order of frequency. Initially second queue is empty.<\/p>\n<p><strong>3.<\/strong> Dequeue two nodes with the minimum frequency by examining the front of both queues. Repeat following steps two times<br \/>\n\u2026..<strong>a)<\/strong> If second queue is empty, dequeue from first queue.<br \/>\n\u2026..<strong>b)<\/strong> If first queue is empty, dequeue from second queue.<br \/>\n\u2026..<strong>c)<\/strong> Else, compare the front of two queues and dequeue the minimum.<\/p>\n<p><strong>4.<\/strong> Create a new internal node with frequency equal to the sum of the two nodes frequencies. Make the first Dequeued node as its left child and the second Dequeued node as right child. Enqueue this node to second queue.<\/p>\n<p><strong>5.<\/strong> Repeat steps#3 and #4 until there is more than one node in the queues. The remaining node is the root node and the tree is complete.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">c<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/\/ C Program for Efficient Huffman Coding for Sorted input<br\/>#include &lt;stdio.h&gt;<br\/>#include &lt;stdlib.h&gt;<br\/> <br\/>\/\/ This constant can be avoided by explicitly calculating height of Huffman Tree<br\/>#define MAX_TREE_HT 100<br\/> <br\/>\/\/ A node of huffman tree<br\/>struct QueueNode<br\/>{<br\/>    char data;<br\/>    unsigned freq;<br\/>    struct QueueNode *left, *right;<br\/>};<br\/> <br\/>\/\/ Structure for Queue: collection of Huffman Tree nodes (or QueueNodes)<br\/>struct Queue<br\/>{<br\/>    int front, rear;<br\/>    int capacity;<br\/>    struct QueueNode **array;<br\/>};<br\/> <br\/>\/\/ A utility function to create a new Queuenode<br\/>struct QueueNode* newNode(char data, unsigned freq)<br\/>{<br\/>    struct QueueNode* temp =<br\/>       (struct QueueNode*) malloc(sizeof(struct QueueNode));<br\/>    temp-&gt;left = temp-&gt;right = NULL;<br\/>    temp-&gt;data = data;<br\/>    temp-&gt;freq = freq;<br\/>    return temp;<br\/>}<br\/> <br\/>\/\/ A utility function to create a Queue of given capacity<br\/>struct Queue* createQueue(int capacity)<br\/>{<br\/>    struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));<br\/>    queue-&gt;front = queue-&gt;rear = -1;<br\/>    queue-&gt;capacity = capacity;<br\/>    queue-&gt;array =<br\/>      (struct QueueNode**) malloc(queue-&gt;capacity * sizeof(struct QueueNode*));<br\/>    return queue;<br\/>}<br\/> <br\/>\/\/ A utility function to check if size of given queue is 1<br\/>int isSizeOne(struct Queue* queue)<br\/>{<br\/>    return queue-&gt;front == queue-&gt;rear &amp;&amp; queue-&gt;front != -1;<br\/>}<br\/> <br\/>\/\/ A utility function to check if given queue is empty<br\/>int isEmpty(struct Queue* queue)<br\/>{<br\/>    return queue-&gt;front == -1;<br\/>}<br\/> <br\/>\/\/ A utility function to check if given queue is full<br\/>int isFull(struct Queue* queue)<br\/>{<br\/>    return queue-&gt;rear == queue-&gt;capacity - 1;<br\/>}<br\/> <br\/>\/\/ A utility function to add an item to queue<br\/>void enQueue(struct Queue* queue, struct QueueNode* item)<br\/>{<br\/>    if (isFull(queue))<br\/>        return;<br\/>    queue-&gt;array[++queue-&gt;rear] = item;<br\/>    if (queue-&gt;front == -1)<br\/>        ++queue-&gt;front;<br\/>}<br\/> <br\/>\/\/ A utility function to remove an item from queue<br\/>struct QueueNode* deQueue(struct Queue* queue)<br\/>{<br\/>    if (isEmpty(queue))<br\/>        return NULL;<br\/>    struct QueueNode* temp = queue-&gt;array[queue-&gt;front];<br\/>    if (queue-&gt;front == queue-&gt;rear)  \/\/ If there is only one item in queue<br\/>        queue-&gt;front = queue-&gt;rear = -1;<br\/>    else<br\/>        ++queue-&gt;front;<br\/>    return temp;<br\/>}<br\/> <br\/>\/\/ A utility function to get from of queue<br\/>struct QueueNode* getFront(struct Queue* queue)<br\/>{<br\/>    if (isEmpty(queue))<br\/>        return NULL;<br\/>    return queue-&gt;array[queue-&gt;front];<br\/>}<br\/> <br\/>\/* A function to get minimum item from two queues *\/<br\/>struct QueueNode* findMin(struct Queue* firstQueue, struct Queue* secondQueue)<br\/>{<br\/>    \/\/ Step 3.a: If second queue is empty, dequeue from first queue<br\/>    if (isEmpty(firstQueue))<br\/>        return deQueue(secondQueue);<br\/> <br\/>    \/\/ Step 3.b: If first queue is empty, dequeue from second queue<br\/>    if (isEmpty(secondQueue))<br\/>        return deQueue(firstQueue);<br\/> <br\/>    \/\/ Step 3.c:  Else, compare the front of two queues and dequeue minimum<br\/>    if (getFront(firstQueue)-&gt;freq &lt; getFront(secondQueue)-&gt;freq)<br\/>        return deQueue(firstQueue);<br\/> <br\/>    return deQueue(secondQueue);<br\/>}<br\/> <br\/>\/\/ Utility function to check if this node is leaf<br\/>int isLeaf(struct QueueNode* root)<br\/>{<br\/>    return !(root-&gt;left) &amp;&amp; !(root-&gt;right) ;<br\/>}<br\/> <br\/>\/\/ A utility function to print an array of size n<br\/>void printArr(int arr[], int n)<br\/>{<br\/>    int i;<br\/>    for (i = 0; i &lt; n; ++i)<br\/>        printf(&quot;%d&quot;, arr[i]);<br\/>    printf(&quot;\\n&quot;);<br\/>}<br\/> <br\/>\/\/ The main function that builds Huffman tree<br\/>struct QueueNode* buildHuffmanTree(char data[], int freq[], int size)<br\/>{<br\/>    struct QueueNode *left, *right, *top;<br\/> <br\/>    \/\/ Step 1: Create two empty queues<br\/>    struct Queue* firstQueue  = createQueue(size);<br\/>    struct Queue* secondQueue = createQueue(size);<br\/> <br\/>    \/\/ Step 2:Create a leaf node for each unique character and Enqueue it to<br\/>    \/\/ the first queue in non-decreasing order of frequency. Initially second<br\/>    \/\/ queue is empty<br\/>    for (int i = 0; i &lt; size; ++i)<br\/>        enQueue(firstQueue, newNode(data[i], freq[i]));<br\/> <br\/>    \/\/ Run while Queues contain more than one node. Finally, first queue will<br\/>    \/\/ be empty and second queue will contain only one node<br\/>    while (!(isEmpty(firstQueue) &amp;&amp; isSizeOne(secondQueue)))<br\/>    {<br\/>        \/\/ Step 3: Dequeue two nodes with the minimum frequency by examining<br\/>        \/\/ the front of both queues<br\/>        left = findMin(firstQueue, secondQueue);<br\/>        right = findMin(firstQueue, secondQueue);<br\/> <br\/>        \/\/ Step 4: Create a new internal node with frequency equal to the sum<br\/>        \/\/ of the two nodes frequencies. Enqueue this node to second queue.<br\/>        top = newNode(&#039;$&#039; , left-&gt;freq + right-&gt;freq);<br\/>        top-&gt;left = left;<br\/>        top-&gt;right = right;<br\/>        enQueue(secondQueue, top);<br\/>    }<br\/> <br\/>    return deQueue(secondQueue);<br\/>}<br\/> <br\/>\/\/ Prints huffman codes from the root of Huffman Tree.  It uses arr[] to<br\/>\/\/ store codes<br\/>void printCodes(struct QueueNode* root, int arr[], int top)<br\/>{<br\/>    \/\/ Assign 0 to left edge and recur<br\/>    if (root-&gt;left)<br\/>    {<br\/>        arr[top] = 0;<br\/>        printCodes(root-&gt;left, arr, top + 1);<br\/>    }<br\/> <br\/>    \/\/ Assign 1 to right edge and recur<br\/>    if (root-&gt;right)<br\/>    {<br\/>        arr[top] = 1;<br\/>        printCodes(root-&gt;right, arr, top + 1);<br\/>    }<br\/> <br\/>    \/\/ If this is a leaf node, then it contains one of the input<br\/>    \/\/ characters, print the character and its code from arr[]<br\/>    if (isLeaf(root))<br\/>    {<br\/>        printf(&quot;%c: &quot;, root-&gt;data);<br\/>        printArr(arr, top);<br\/>    }<br\/>}<br\/> <br\/>\/\/ The main function that builds a Huffman Tree and print codes by traversing<br\/>\/\/ the built Huffman Tree<br\/>void HuffmanCodes(char data[], int freq[], int size)<br\/>{<br\/>   \/\/  Construct Huffman Tree<br\/>   struct QueueNode* root = buildHuffmanTree(data, freq, size);<br\/> <br\/>   \/\/ Print Huffman codes using the Huffman tree built above<br\/>   int arr[MAX_TREE_HT], top = 0;<br\/>   printCodes(root, arr, top);<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    char arr[] = {&#039;a&#039;, &#039;b&#039;, &#039;c&#039;, &#039;d&#039;, &#039;e&#039;, &#039;f&#039;};<br\/>    int freq[] = {5, 9, 12, 13, 16, 45};<br\/>    int size = sizeof(arr)\/sizeof(arr[0]);<br\/>    HuffmanCodes(arr, freq, size);<br\/>    return 0;<br\/>}<br\/>Run on IDE<\/code><\/pre> <\/div>\n<h4 id=\"output\"><strong>Output:<\/strong><\/h4>\n<pre>f: 0\r\nc: 100\r\nd: 101\r\na: 1100\r\nb: 1101\r\ne: 111<\/pre>\n<p><strong>Time complexity:<\/strong> O(n)<\/p>\n<p>If the input is not sorted, it need to be sorted first before it can be processed by the above algorithm. Sorting can be done using heap-sort or merge-sort both of which run in Theta(nlogn). So, the overall time complexity becomes O(nlogn) for unsorted input.<\/p>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Efficient Huffman Coding for Sorted Input &#8211; Greedy Algorithm &#8211; Time complexity of the algorithm discussed in above post is O(nLogn). If we know that the given array is sorted (by non-decreasing order of frequency).<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,83476],"tags":[71215,71202,71082,71195,71197,71090,71067,71203,71084,71200,71208,71207,71199,71097,71113,71114,71068,71119,71209,70480,71079,71112,71116,71083,71085,71204,71103,71091,71108,71101,71201,71089,71100,71107,71213,71086,71206,71080,71088,71118,71214,71205,71212,71211,71115,71087,71099,71105,71109,71092,71117,71210,71193,71194,71111,71073,71064,71071,71192,71196,71198,71102],"class_list":["post-25081","post","type-post","status-publish","format-standard","hentry","category-coding","category-huffman-coding","tag-adaptive-huffman-coding-in-c","tag-adaptive-huffman-coding-tree-example","tag-application-of-huffman-coding-in-data-compression","tag-arithmetic-coding-for-data-compression-example","tag-binary-code-example","tag-c-program-to-implement-huffman-code","tag-codetree","tag-coding-algorithms","tag-encoding-and-decoding-huffman-code-in-java","tag-example-of-encoding","tag-example-of-huffman-coding","tag-examples-of-trees","tag-ffman-coding-in-c-huffman-program-in-c","tag-frequency-tree","tag-half-man-coding","tag-how-to-find-codeword-in-huffman-coding","tag-huffman-algorithm-in-data-structure","tag-huffman-algorithm-java","tag-huffman-code-tree-generator","tag-huffman-coding","tag-huffman-coding-algorithm-in-c","tag-huffman-coding-algorithm-in-matlab","tag-huffman-coding-animation","tag-huffman-coding-example","tag-huffman-coding-example-pdf","tag-huffman-coding-implementation","tag-huffman-coding-in-c-language","tag-huffman-coding-in-c-using-array","tag-huffman-coding-in-matlab-program","tag-huffman-coding-matlab-program","tag-huffman-coding-ppt-presentation","tag-huffman-coding-program-in-c","tag-huffman-coding-program-in-c-with-output","tag-huffman-coding-program-in-java","tag-huffman-coding-simple-program-in-c","tag-huffman-coding-steps","tag-huffman-coding-using-matlab","tag-huffman-coding-with-example","tag-huffman-compression-algorithm","tag-huffman-encoding-and-decoding-example-in-java","tag-huffman-encoding-and-decoding-in-c","tag-huffman-encoding-and-decoding-in-matlab","tag-huffman-encoding-in-c","tag-huffman-encoding-online","tag-huffman-encoding-tree","tag-huffman-tree","tag-huffman-tree-c","tag-implementation-of-huffman-coding-in-c","tag-online-huffman-encoder","tag-optimal-huffman-code","tag-program-for-huffman-coding-in-c","tag-shannon-coding-example","tag-shannon-fano-algorithm","tag-shannon-fano-coding-example","tag-simple-huffman-coding-c","tag-simple-huffman-coding-in-c","tag-source-code-for-huffman-coding-in-c","tag-tree-code","tag-tree-tutorial","tag-variance-symbol","tag-write-a-program-for-hu","tag-write-a-program-for-huffman-coding"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25081","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=25081"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/25081\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=25081"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=25081"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=25081"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}