{"id":27684,"date":"2018-04-09T20:21:01","date_gmt":"2018-04-09T14:51:01","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27684"},"modified":"2018-09-14T18:53:16","modified_gmt":"2018-09-14T13:23:16","slug":"python-programming-heap-sort","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-heap-sort\/","title":{"rendered":"python 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=\"python-programming\">PYTHON programming:<\/h2>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program for implementation of heap Sort<br\/> <br\/># To heapify subtree rooted at index i.<br\/># n is size of heap<br\/>def heapify(arr, n, i):<br\/>    largest = i  # Initialize largest as root<br\/>    l = 2 * i + 1     # left = 2*i + 1<br\/>    r = 2 * i + 2     # right = 2*i + 2<br\/> <br\/>    # See if left child of root exists and is<br\/>    # greater than root<br\/>    if l &lt; n and arr[i] &lt; arr[l]:<br\/>        largest = l<br\/> <br\/>    # See if right child of root exists and is<br\/>    # greater than root<br\/>    if r &lt; n and arr[largest] &lt; arr[r]:<br\/>        largest = r<br\/> <br\/>    # Change root, if needed<br\/>    if largest != i:<br\/>        arr[i],arr[largest] = arr[largest],arr[i]  # swap<br\/> <br\/>        # Heapify the root.<br\/>        heapify(arr, n, largest)<br\/> <br\/># The main function to sort an array of given size<br\/>def heapSort(arr):<br\/>    n = len(arr)<br\/> <br\/>    # Build a maxheap.<br\/>    for i in range(n, -1, -1):<br\/>        heapify(arr, n, i)<br\/> <br\/>    # One by one extract elements<br\/>    for i in range(n-1, 0, -1):<br\/>        arr[i], arr[0] = arr[0], arr[i]   # swap<br\/>        heapify(arr, i, 0)<br\/> <br\/># Driver code to test above<br\/>arr = [ 12, 11, 13, 5, 6, 7]<br\/>heapSort(arr)<br\/>n = len(arr)<br\/>print (&quot;Sorted array is&quot;)<br\/>for i in range(n):<br\/>    print (&quot;%d&quot; %arr[i]),<\/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":[81971,81974,81948,81972,81975,81970,81976,81973],"class_list":["post-27684","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures","category-heap","tag-heap-data-structure-python","tag-heap-sort-pseudocode","tag-heapsort-explained","tag-heapsort-wiki","tag-how-does-heapsort-work","tag-max-heapify-python","tag-quick-sort-python","tag-shell-sort-python"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27684","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=27684"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27684\/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=27684"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27684"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27684"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}