{"id":26948,"date":"2018-01-02T20:37:21","date_gmt":"2018-01-02T15:07:21","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26948"},"modified":"2018-01-02T20:37:21","modified_gmt":"2018-01-02T15:07:21","slug":"c-programming-binary-heap","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-binary-heap\/","title":{"rendered":"C++ programming  Binary heap"},"content":{"rendered":"<p>A Binary Heap is a Binary Tree with following properties.<\/p>\n<p>1) It\u2019s a complete tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.<\/p>\n<p>2) A Binary Heap is either Min Heap or Max Heap. In a Min Binary Heap, the key at root must be minimum among all keys present in Binary Heap. The same property must be recursively true for all nodes in Binary Tree. Max Binary Heap is similar to Min heap.<\/p>\n<p><strong>How is Binary Heap represented?<\/strong><br \/>\nA Binary Heap is a Complete Binary Tree. A binary heap is typically represented as array. Please refer below article for details.<br \/>\n<a href=\"http:\/\/quiz.geeksforgeeks.org\/array-representation-of-binary-heap\/\" target=\"_blank\" rel=\"noopener\">Array Representation Of Binary Heap<\/a><\/p>\n<p><strong>Applications of Heaps:<\/strong><br \/>\n<strong>1)<\/strong> <a href=\"http:\/\/quiz.geeksforgeeks.org\/heap-sort\/\" target=\"_blank\" rel=\"noopener noreferrer\">Heap Sort<\/a>: Heap Sort uses Binary Heap to sort an array in O(nLogn) time.<\/p>\n<p><strong>2)<\/strong> Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time. Binomoial Heap and Fibonacci Heap are variations of Binary Heap. These variations perform union also efficiently.<\/p>\n<p><strong>3) <\/strong>Graph Algorithms: The priority queues are especially used in Graph Algorithms like <a href=\"http:\/\/www.geeksforgeeks.org\/greedy-algorithms-set-7-dijkstras-algorithm-for-adjacency-list-representation\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dijkstra\u2019s Shortest Path<\/a> and<a href=\"http:\/\/www.geeksforgeeks.org\/greedy-algorithms-set-5-prims-minimum-spanning-tree-mst-2\/\" target=\"_blank\" rel=\"noopener noreferrer\"> Prim\u2019s Minimum Spanning Tree<\/a>.<\/p>\n<p><strong>4)<\/strong> Many problems can be efficiently solved using Heaps. See following for example.<br \/>\na) <a href=\"http:\/\/www.geeksforgeeks.org\/k-largestor-smallest-elements-in-an-array\/\" target=\"_blank\" rel=\"noopener noreferrer\">K\u2019th Largest Element in an array<\/a>.<br \/>\nb) <a href=\"http:\/\/www.geeksforgeeks.org\/nearly-sorted-algorithm\/\" target=\"_blank\" rel=\"noopener noreferrer\">Sort an almost sorted array\/<\/a><br \/>\nc) <a href=\"http:\/\/www.geeksforgeeks.org\/merge-k-sorted-arrays\/\" target=\"_blank\" rel=\"noopener noreferrer\">Merge K Sorted Arrays<\/a>.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Operations on Min Heap:<\/strong><br \/>\n<strong>1)<\/strong> getMini(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).<\/p>\n<p><strong>2)<\/strong> extractMin(): Removes the minimum element from Min Heap. Time Complexity of this Operation is O(Logn) as this operation needs to maintain the heap property (by calling heapify()) after removing root.<\/p>\n<p><strong>3)<\/strong> decreaseKey(): Decreases value of key. Time complexity of this operation is O(Logn). If the decreases key value of a node is greater than parent of the node, then we don\u2019t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.<\/p>\n<p><strong>4) <\/strong>insert(): Inserting a new key takes O(Logn) time. We add a new key at the end of the tree. IF new key is greater than its parent, then we don\u2019t need to do anything. Otherwise, we need to traverse up to fix the violated heap property.<\/p>\n<p><strong>5)<\/strong> delete(): Deleting a key also takes O(Logn) time. We replace the key to be deleted with minum infinite by calling decreaseKey(). After decreaseKey(), the minus infinite value must reach root, so we call extractMin() to remove key.<\/p>\n<p>C++ prorgramming:<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ A C++ program to demonstrate common Binary Heap Operations<br\/>#include&lt;iostream&gt;<br\/>#include&lt;climits&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ Prototype of a utility function to swap two integers<br\/>void swap(int *x, int *y);<br\/> <br\/>\/\/ A class for Min Heap<br\/>class MinHeap<br\/>{<br\/>    int *harr; \/\/ pointer to array of elements in heap<br\/>    int capacity; \/\/ maximum possible size of min heap<br\/>    int heap_size; \/\/ Current number of elements in min heap<br\/>public:<br\/>    \/\/ Constructor<br\/>    MinHeap(int capacity);<br\/> <br\/>    \/\/ to heapify a subtree with root at given index<br\/>    void MinHeapify(int );<br\/> <br\/>    int parent(int i) { return (i-1)\/2; }<br\/> <br\/>    \/\/ to get index of left child of node at index i<br\/>    int left(int i) { return (2*i + 1); }<br\/> <br\/>    \/\/ to get index of right child of node at index i<br\/>    int right(int i) { return (2*i + 2); }<br\/> <br\/>    \/\/ to extract the root which is the minimum element<br\/>    int extractMin();<br\/> <br\/>    \/\/ Decreases key value of key at index i to new_val<br\/>    void decreaseKey(int i, int new_val);<br\/> <br\/>    \/\/ Returns the minimum key (key at root) from min heap<br\/>    int getMin() { return harr[0]; }<br\/> <br\/>    \/\/ Deletes a key stored at index i<br\/>    void deleteKey(int i);<br\/> <br\/>    \/\/ Inserts a new key &#039;k&#039;<br\/>    void insertKey(int k);<br\/>};<br\/> <br\/>\/\/ Constructor: Builds a heap from a given array a[] of given size<br\/>MinHeap::MinHeap(int cap)<br\/>{<br\/>    heap_size = 0;<br\/>    capacity = cap;<br\/>    harr = new int[cap];<br\/>}<br\/> <br\/>\/\/ Inserts a new key &#039;k&#039;<br\/>void MinHeap::insertKey(int k)<br\/>{<br\/>    if (heap_size == capacity)<br\/>    {<br\/>        cout &lt;&lt; &quot;\\nOverflow: Could not insertKey\\n&quot;;<br\/>        return;<br\/>    }<br\/> <br\/>    \/\/ First insert the new key at the end<br\/>    heap_size++;<br\/>    int i = heap_size - 1;<br\/>    harr[i] = k;<br\/> <br\/>    \/\/ Fix the min heap property if it is violated<br\/>    while (i != 0 &amp;&amp; harr[parent(i)] &gt; harr[i])<br\/>    {<br\/>       swap(&amp;harr[i], &amp;harr[parent(i)]);<br\/>       i = parent(i);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Decreases value of key at index &#039;i&#039; to new_val.  It is assumed that<br\/>\/\/ new_val is smaller than harr[i].<br\/>void MinHeap::decreaseKey(int i, int new_val)<br\/>{<br\/>    harr[i] = new_val;<br\/>    while (i != 0 &amp;&amp; harr[parent(i)] &gt; harr[i])<br\/>    {<br\/>       swap(&amp;harr[i], &amp;harr[parent(i)]);<br\/>       i = parent(i);<br\/>    }<br\/>}<br\/> <br\/>\/\/ Method to remove minimum element (or root) from min heap<br\/>int MinHeap::extractMin()<br\/>{<br\/>    if (heap_size &lt;= 0)<br\/>        return INT_MAX;<br\/>    if (heap_size == 1)<br\/>    {<br\/>        heap_size--;<br\/>        return harr[0];<br\/>    }<br\/> <br\/>    \/\/ Store the minimum value, and remove it from heap<br\/>    int root = harr[0];<br\/>    harr[0] = harr[heap_size-1];<br\/>    heap_size--;<br\/>    MinHeapify(0);<br\/> <br\/>    return root;<br\/>}<br\/> <br\/> <br\/>\/\/ This function deletes key at index i. It first reduced value to minus<br\/>\/\/ infinite, then calls extractMin()<br\/>void MinHeap::deleteKey(int i)<br\/>{<br\/>    decreaseKey(i, INT_MIN);<br\/>    extractMin();<br\/>}<br\/> <br\/>\/\/ A recursive method to heapify a subtree with root at given index<br\/>\/\/ This method assumes that the subtrees are already heapified<br\/>void MinHeap::MinHeapify(int i)<br\/>{<br\/>    int l = left(i);<br\/>    int r = right(i);<br\/>    int smallest = i;<br\/>    if (l &lt; heap_size &amp;&amp; harr[l] &lt; harr[i])<br\/>        smallest = l;<br\/>    if (r &lt; heap_size &amp;&amp; harr[r] &lt; harr[smallest])<br\/>        smallest = r;<br\/>    if (smallest != i)<br\/>    {<br\/>        swap(&amp;harr[i], &amp;harr[smallest]);<br\/>        MinHeapify(smallest);<br\/>    }<br\/>}<br\/> <br\/>\/\/ A utility function to swap two elements<br\/>void swap(int *x, int *y)<br\/>{<br\/>    int temp = *x;<br\/>    *x = *y;<br\/>    *y = temp;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    MinHeap h(11);<br\/>    h.insertKey(3);<br\/>    h.insertKey(2);<br\/>    h.deleteKey(1);<br\/>    h.insertKey(15);<br\/>    h.insertKey(5);<br\/>    h.insertKey(4);<br\/>    h.insertKey(45);<br\/>    cout &lt;&lt; h.extractMin() &lt;&lt; &quot; &quot;;<br\/>    cout &lt;&lt; h.getMin() &lt;&lt; &quot; &quot;;<br\/>    h.decreaseKey(2, 1);<br\/>    cout &lt;&lt; h.getMin();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>2 4 1<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>C++ programming Binary heap &#8211; Binary heap &#8211; It\u2019s complete tree (All levels are completely filled except possibly the last level and the last level).<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,80127],"tags":[80475,80476,80474,80471,80472,80469,80470,80473],"class_list":["post-26948","post","type-post","status-publish","format-standard","hentry","category-data-structures","category-heap","tag-binary-heap-implementation-in-c","tag-binary-heap-priority-queue-c","tag-build-heap-c","tag-heap-c-geeksforgeeks","tag-heap-implementation-in-c-using-priority-queue","tag-max-heap-implementation-c","tag-min-and-max-heap-tree-code-for-c","tag-min-heap-implementation-geeksforgeeks"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26948","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=26948"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26948\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26948"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26948"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26948"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}