{"id":27642,"date":"2018-04-04T19:36:48","date_gmt":"2018-04-04T14:06:48","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27642"},"modified":"2018-09-16T14:34:10","modified_gmt":"2018-09-16T09:04:10","slug":"heap-sort-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/heap-sort-2\/","title":{"rendered":"C++ programming Heap Sort"},"content":{"rendered":"<p>Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.<\/p>\n<p><strong>What is <a href=\"http:\/\/geeksquiz.com\/binary-heap\/\" target=\"_blank\" rel=\"noopener\">Binary Heap<\/a>?<\/strong><br \/>\nLet us first define a Complete Binary Tree. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible (Source <a href=\"http:\/\/en.wikipedia.org\/wiki\/Binary_tree#Types_of_binary_trees\" target=\"_blank\" rel=\"noopener noreferrer\">Wikipedia<\/a>)<\/p>\n<p>A <a href=\"http:\/\/geeksquiz.com\/binary-heap\/\" target=\"_blank\" rel=\"noopener\">Binary Heap<\/a> is a Complete Binary Tree where items are stored in a special order such that value in a parent node is greater(or smaller) than the values in its two children nodes. The former is called as max heap and the latter is called min heap. The heap can be represented by binary tree or array.<\/p>\n<p><strong>Why array based representation for Binary Heap?<\/strong><br \/>\nSince a Binary Heap is a Complete Binary Tree, it can be easily represented as array and array based representation is space efficient. If the parent node is stored at index I, the left child can be calculated by 2 * I + 1 and right child by 2 * I + 2 (assuming the indexing starts at 0).<\/p>\n<p><strong>Heap Sort Algorithm for sorting in increasing order:<\/strong><br \/>\n<strong>1.<\/strong> Build a max heap from the input data.<br \/>\n<strong>2.<\/strong> At this point, the largest item is stored at the root of the heap. Replace it with the last item of the heap followed by reducing the size of heap by 1. Finally, heapify the root of tree.<br \/>\n<strong>3.<\/strong> Repeat above steps while size of heap is greater than 1.<\/p>\n<p><strong>How to build the heap?<\/strong><br \/>\nHeapify procedure can be applied to a node only if its children nodes are heapified. So the heapification must be performed in the bottom up order.<\/p>\n<p>Lets understand with the help of an example:<\/p>\n<pre>Input data: 4, 10, 3, 5, 1\r\n                 4(0)\r\n\t\t\/   \\\r\n\t     10(1)   3(2)\r\n            \/   \\\r\n\t 5(3)    1(4)\r\n\r\nThe numbers in bracket represent the indices in the array \r\nrepresentation of data.\r\n\r\nApplying heapify procedure to index 1:\r\n \t\t4(0)\r\n\t\t\/   \\\r\n            10(1)    3(2)\r\n           \/   \\\r\n\t5(3)    1(4)\r\n\r\nApplying heapify procedure to index 0:\r\n\t        10(0)\r\n\t\t\/  \\\r\n\t     5(1)  3(2)\r\n            \/   \\\r\n         4(3)    1(4)\r\nThe heapify procedure calls itself recursively to build heap\r\n in top down manner.\r\n<\/pre>\n<div id=\"practice\">\n<h2 id=\"c-programming\">C++ programming:<\/h2>\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\">\/\/ C++ program for implementation of Heap Sort<br\/>#include &lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/\/ To heapify a subtree rooted with node i which is<br\/>\/\/ an index in arr[]. n is size of heap<br\/>void heapify(int arr[], int n, int i)<br\/>{<br\/>    int largest = i;  \/\/ Initialize largest as root<br\/>    int l = 2*i + 1;  \/\/ left = 2*i + 1<br\/>    int r = 2*i + 2;  \/\/ right = 2*i + 2<br\/> <br\/>    \/\/ If left child is larger than root<br\/>    if (l &lt; n &amp;&amp; arr[l] &gt; arr[largest])<br\/>        largest = l;<br\/> <br\/>    \/\/ If right child is larger than largest so far<br\/>    if (r &lt; n &amp;&amp; arr[r] &gt; arr[largest])<br\/>        largest = r;<br\/> <br\/>    \/\/ If largest is not root<br\/>    if (largest != i)<br\/>    {<br\/>        swap(arr[i], arr[largest]);<br\/> <br\/>        \/\/ Recursively heapify the affected sub-tree<br\/>        heapify(arr, n, largest);<br\/>    }<br\/>}<br\/> <br\/>\/\/ main function to do heap sort<br\/>void heapSort(int arr[], int n)<br\/>{<br\/>    \/\/ Build heap (rearrange array)<br\/>    for (int i = n \/ 2 - 1; i &gt;= 0; i--)<br\/>        heapify(arr, n, i);<br\/> <br\/>    \/\/ One by one extract an element from heap<br\/>    for (int i=n-1; i&gt;=0; i--)<br\/>    {<br\/>        \/\/ Move current root to end<br\/>        swap(arr[0], arr[i]);<br\/> <br\/>        \/\/ call max heapify on the reduced heap<br\/>        heapify(arr, i, 0);<br\/>    }<br\/>}<br\/> <br\/>\/* A utility function to print array of size n *\/<br\/>void printArray(int arr[], int n)<br\/>{<br\/>    for (int i=0; i&lt;n; ++i)<br\/>        cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;<br\/>    cout &lt;&lt; &quot;\\n&quot;;<br\/>}<br\/> <br\/>\/\/ Driver program<br\/>int main()<br\/>{<br\/>    int arr[] = {12, 11, 13, 5, 6, 7};<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/> <br\/>    heapSort(arr, n);<br\/> <br\/>    cout &lt;&lt; &quot;Sorted array is \\n&quot;;<br\/>    printArray(arr, n);<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Sorted array is\r\n5 6 7 11 12 13<\/pre>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element. What is Binary Heap? Let us first define a Complete Binary Tree. [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":31271,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[73012,80127],"tags":[70876,81915,81916,81914,81912,81911,81913,81910],"class_list":["post-27642","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures","category-heap","tag-heap-sort-algorithm-in-data-structure","tag-heap-sort-c-vector","tag-heap-sort-code-java","tag-heap-sort-program-in-c-using-class","tag-heap-sort-program-in-c-with-explanation","tag-heapsort-c-code-explained","tag-min-heap-sort-c","tag-write-a-c-program-to-implement-heap-sort"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27642","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=27642"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27642\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31271"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27642"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27642"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27642"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}