{"id":116,"date":"2026-11-13T12:31:48","date_gmt":"2026-11-13T04:31:48","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-binary-heap-sifts-in-an-array\/"},"modified":"2026-11-13T21:50:40","modified_gmt":"2026-11-13T13:50:40","slug":"how-a-binary-heap-sifts-in-an-array","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-binary-heap-sifts-in-an-array\/","title":{"rendered":"How a binary heap sifts in an array"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> A <strong>binary heap<\/strong> stores a complete binary tree in an array. The parent of index i is floor((i\u22121)\/2), and the children are 2i+1 and 2i+2, for zero-based indexes. The heap property says every parent is ordered before its children. <strong>Sift up<\/strong> repairs an insertion at the end. <strong>Sift down<\/strong> repairs a hole. Building a heap from an array by sifting down from the last parent is <strong>\u0398(n)<\/strong>. Each later insert or extract is <strong>O(log n)<\/strong>.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">A priority queue needs the minimum, or the maximum, and it needs to insert a key, faster than a sorted array and with better locality than a pointer tree. The complete binary tree fills indices with no gaps, so the children of i are arithmetic rather than pointers. The only invariant a sift has to restore is the parent-child order along one path.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The linear build is the fact most often missed. Inserting n keys one by one is O(n log n). Sifting down from the middle of the array is linear because most subtrees are short.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Insert and decrease-key, implemented as sift up, are O(log n). Extract-min and delete, implemented as moving the last leaf into the hole and sifting down, are O(log n). Heapify is \u0398(n). Extra memory is the array itself. A binary heap does not find an arbitrary key quickly, and it does not keep a stable order among equal keys unless an explicit counter is added to the comparison.<\/p>\n\n\n<p class=\"wp-block-paragraph\">Decrease-key needs the index of the element inside the array. A heap of bare values, with no handle map, cannot decrease a key that the caller only knows by identity. Dijkstra&#8217;s algorithm needs those handles, or it must push duplicate entries and ignore stale ones.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>Store the heap in a dynamic array. The minimum sits at index 0 in a min-heap.<\/li>\n<li>To insert, append the key and sift up: while the key is smaller than its parent, swap them.<\/li>\n<li>To extract the minimum, read index 0, move the last element into index 0, shrink the array, and sift down. Sift down swaps with the smaller child until the parent is smaller than both children or a leaf is reached.<\/li>\n<li>To heapify an array, sift down from index floor(n\/2)\u22121 through 0.<\/li>\n<li>To decrease a key, write the new value at its index and sift up. The caller must have the index.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">The logarithmic bound is one sift along a root path. It is not a sorted array, and a search for a non-extremal key is linear. A Fibonacci heap improves the amortized cost of decrease-key to constant time and is rarely faster in practice. A binary heap is the default priority queue.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when the array indexes are one-based in a zero-based language<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Use children 2i and 2i+1 on a zero-based array<\/td>\n<td>Index 0 then points at itself as a child. Zero-based children are 2i+1 and 2i+2.<\/td>\n<\/tr>\n<tr>\n<td>Build the heap by n insertions and quote a linear build<\/td>\n<td>n insertions cost O(n log n). The linear bound is the bottom-up sift from the last parent.<\/td>\n<\/tr>\n<tr>\n<td>Sift up during that bottom-up build<\/td>\n<td>Sift up walks toward the root from every node and loses the linear bound. Construction moves the hole downward.<\/td>\n<\/tr>\n<tr>\n<td>Decrease a key without its index<\/td>\n<td>The value may sit anywhere. Finding it is a scan. Dijkstra needs a handle or a duplicate-entry convention.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">A worst-case in-place sort built from this heap is heapsort. A decrease-key with an amortized constant bound is the Fibonacci heap. A balanced search tree sorts keys and also finds arbitrary ones, which a heap does not.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">This Python fragment sifts a binary heap stored in an array and extracts the minimums. Children of i are 2i+1 and 2i+2. It prints <code>1 2 3 4<\/code>.<\/p>\n\n<pre><code class=\"language-python\">def heapify(a, n, i):\n    while True:\n        left, right, best = 2 * i + 1, 2 * i + 2, i\n        if left &lt; n and a[left] &lt; a[best]:\n            best = left\n        if right &lt; n and a[right] &lt; a[best]:\n            best = right\n        if best == i:\n            return\n        a[i], a[best] = a[best], a[i]\n        i = best\n\ndef build(a):\n    for i in range(len(a) \/\/ 2 - 1, -1, -1):\n        heapify(a, len(a), i)\n\ndef extract(a):\n    last = a.pop()\n    if not a:\n        return last\n    root, a[0] = a[0], last\n    heapify(a, len(a), 0)\n    return root\n\nh = [4, 1, 3, 2]\nbuild(h)\nprint(*(extract(h) for _ in range(4)))\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The binary heap is the priority queue in <strong>Python&#8217;s <code>heapq<\/code><\/strong>, Java&#8217;s <code>PriorityQueue<\/code>, and C++ <code>priority_queue<\/code>. Dijkstra and event simulations pull the next earliest item from that array. A red-black tree can order the same keys, at the cost of pointers the heap does not store.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">Drop a binary heap when the access pattern is a full sort of a static array. Heapsort or a library sort is the direct tool. Keep the heap for a priority queue, for Dijkstra, and for a linear heapify when only the parent-child order is required.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">We publish this so a search for a binary heap returns the zero-based child indexes and the linear bottom-up heapify. <strong>A binary heap implements a priority queue in an array with O(log n) sifts, and it builds from an unsorted array in linear time by sifting down from the last parent.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Short answer: A binary heap stores a complete binary tree in an array. The parent of index i is floor((i\u22121)\/2), and the children are 2i+1 and 2i+2, for zero-based indexes. The heap property says every parent is ordered before its children. Sift up repairs an insertion at the end.&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,35],"tags":[],"class_list":["post-116","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-heaps"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/116","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=116"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/116\/revisions"}],"predecessor-version":[{"id":515,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/116\/revisions\/515"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=116"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=116"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=116"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}