{
  "id": "binary-heap",
  "title": "Binary Heap",
  "lang": "en",
  "source_lang": "en",
  "summary": "A binary heap is a complete binary tree with an ordering constraint that supports efficient access to and removal of the minimum or maximum element.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/binary-heap/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/binary-heap/",
      "json": "https://aiwiki.page/zh/binary-heap.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A binary heap is a data structure organized as a complete binary tree in which each parent’s key is ordered relative to its children. In a min-heap, every parent’s key is no greater than its children’s keys; in a max-heap, it is no smaller. Consequently, the root contains a minimum or maximum key, respectively. Binary heaps are commonly stored in arrays and are widely used to implement priority queues and the heapsort algorithm."
    },
    {
      "heading": "Structure and ordering",
      "text": "A binary heap satisfies two independent conditions:\n\n- Shape property: Every level is full except possibly the lowest, which is filled from left to right.\n- Heap-order property: Each parent precedes or ties its children under the chosen priority ordering.\n\nFor a min-heap with key function \\(k\\), the ordering condition is\n\n\\[k(\\operatorname{parent}(v)) \\leq k(v)\\]\n\nfor every non-root node \\(v\\). A max-heap reverses the inequality. Duplicate keys are permitted.\n\nThe shape property ensures that a nonempty heap containing \\(n\\) elements has height\n\n\\[h=\\lfloor \\log_2 n \\rfloor,\\]\n\nwhen height is measured in edges. This logarithmic height bounds the number of levels traversed during insertion and removal.\n\nHeap order is only a partial ordering of the elements. It constrains ancestors and descendants but does not generally order siblings or elements in separate subtrees. For example, the array\n\n[2, 5, 3, 9, 7, 8, 4]\n\nrepresents a valid min-heap even though the array is not sorted.\n\nA binary heap is therefore different from a binary search tree. A search tree orders keys across its left and right subtrees to support search; a heap makes an extreme key immediately available without maintaining enough order for efficient arbitrary-key lookup."
    },
    {
      "heading": "Array representation",
      "text": "A binary heap is usually represented by an array rather than by individually allocated nodes with pointers. Completeness allows the tree’s relationships to be recovered directly from array positions.\n\nFor zero-based indexing, a node at index \\(i\\) has:\n\n\\[\\operatorname{parent}(i)=\\left\\lfloor\\frac{i-1}{2}\\right\\rfloor \\quad \\text{for } i>0,\\]\n\n\\[\\operatorname{left}(i)=2i+1, \\qquad \\operatorname{right}(i)=2i+2.\\]\n\nA child exists only if its index is less than the current heap size \\(n\\). With one-based indexing, the corresponding indices are \\(\\lfloor i/2\\rfloor\\), \\(2i\\), and \\(2i+1\\).\n\nThis representation requires no explicit links between nodes and stores the heap in level order. It has low per-element overhead and generally favorable spatial locality, although root-to-leaf paths can still span multiple cache lines in large heaps.\n\nThe heap’s logical size must be distinguished from its array capacity. Slots beyond the logical size are not part of the heap."
    },
    {
      "heading": "Fundamental operations",
      "text": "The following descriptions use a min-heap. Max-heap operations reverse the comparisons.\n\nInspecting the minimum\n\nThe minimum is stored at the root, so inspecting it takes \\(O(1)\\) time. The operation is undefined for an empty heap unless the interface specifies an error, sentinel, or optional result.\n\nInsertion and sift-up\n\nInsertion first appends an element at the next available position, preserving completeness. The element is then compared with its parent. If its key is smaller, it is exchanged with the parent, and the process continues upward.\n\nThis operation is called sift-up, bubble-up, or percolate-up. Only the newly introduced ancestor path can violate heap order, so repairing that path restores the invariant.\n\nInsertion requires \\(O(\\log n)\\) heap work in the worst case. If the backing array must grow, an individual insertion may additionally require \\(O(n)\\) copying or movement. With geometric capacity growth, the array-growth contribution is \\(O(1)\\) amortized per insertion.\n\nRemoving the minimum and sift-down\n\nTo remove the root:\n\n- Save the root element.\n- Move the last element into the root position and reduce the heap size.\n- Compare the replacement with its children.\n- If it is greater than the smaller child, exchange them and continue downward.\n\nThis repair operation is called sift-down, bubble-down, or percolate-down. Choosing the smaller child is essential: moving the larger child upward could leave it greater than its sibling.\n\nRemoval takes \\(O(\\log n)\\) time in the worst case. A one-element heap simply becomes empty.\n\nThe following pseudocode performs sift-down in a zero-indexed min-heap, assuming that the child subtrees already satisfy heap order:\n\nsift_down(A, i, n):\n    while 2*i + 1 < n:\n        child = 2*i + 1\n        right = child + 1\n\n        if right < n and A[right] < A[child]:\n            child = right\n\n        if A[i] <= A[child]:\n            break\n\n        swap A[i], A[child]\n        i = child\n\nImplementations may move elements through a temporary “hole” rather than repeatedly swapping them, reducing assignments while preserving the same asymptotic bound.\n\nChanging priorities and deleting known elements\n\nIf an element’s position is known, decreasing its key in a min-heap may require sift-up; increasing its key may require sift-down. Either operation takes \\(O(\\log n)\\) time.\n\nAn arbitrary element at a known position can be deleted by replacing it with the last element and repairing upward or downward as appropriate. This also takes \\(O(\\log n)\\).\n\nThe qualification “position is known” matters. Searching for a particular value in an ordinary binary heap takes \\(O(n)\\) time in the worst case. An indexed priority queue maintains an additional mapping from element identifiers to heap positions, often using an array or hash table. Every movement within the heap must update that mapping."
    },
    {
      "heading": "Building a heap",
      "text": "A heap can be built by repeatedly inserting elements, which takes \\(O(n\\log n)\\) time in the worst case. A more efficient method constructs it bottom-up.\n\nFor a zero-indexed array of length \\(n\\), all positions from \\(\\lfloor n/2\\rfloor\\) onward are leaves and already satisfy heap order individually. Starting at the last internal node, \\(\\lfloor n/2\\rfloor-1\\), the algorithm applies sift-down at each position in reverse order until it reaches the root.\n\nThis procedure, commonly called bottom-up heap construction or build-heap, takes \\(\\Theta(n)\\) time. It is often associated with Robert W. Floyd’s work on heapsort.\n\nThe linear bound follows because most nodes are near the leaves and can move only a short distance. An upper bound on the total work is proportional to\n\n\\[n\\sum_{h=0}^{\\lfloor\\log_2 n\\rfloor}\\frac{h}{2^{h+1}} =O(n).\\]\n\nAlthough one sift-down can cost \\(O(\\log n)\\), only a small fraction of nodes have that much height available. Multiplying the maximum sift-down cost by every node therefore gives a loose bound.\n\nThe term heapify is ambiguous: some interfaces use it for building an entire heap, while some algorithm descriptions use it for a single sift-down operation."
    },
    {
      "heading": "Complexity",
      "text": "Under the usual model of constant-time key comparison and element movement, the main time complexities are:\n\nOperation | Time bound\nInspect minimum or maximum | \\(O(1)\\)\nInsert, excluding array reallocation | \\(O(\\log n)\\) worst case\nRemove minimum or maximum | \\(O(\\log n)\\) worst case\nChange key at a known position | \\(O(\\log n)\\) worst case\nDelete at a known position | \\(O(\\log n)\\) worst case\nSearch for an arbitrary key | \\(O(n)\\) worst case\nBottom-up construction | \\(\\Theta(n)\\)\nMerge two heaps by concatenation and rebuilding | \\(\\Theta(n+m)\\)\n\nStorage for \\(n\\) elements is \\(O(n)\\). Iterative sift-up and sift-down use \\(O(1)\\) auxiliary space. Recursive implementations may instead use \\(O(\\log n)\\) call-stack space.\n\nThese bounds exclude costs intrinsic to the stored objects. Comparing long strings or moving large records can make a nominally constant-time step more expensive."
    },
    {
      "heading": "Applications",
      "text": "Priority queues\n\nA priority queue is an abstract data type specifying operations such as insertion and removal of the highest-priority item; a binary heap is one concrete implementation.\n\nHeap-based priority queues support event simulation, task selection, and scheduling systems in which the next item is determined by priority rather than arrival order.\n\nThey are also used in graph algorithms. Dijkstra’s algorithm can use a min-heap to select the next vertex with the smallest tentative distance, while A* search orders candidates by estimated total path cost. Implementations may support direct priority updates or insert revised entries and ignore obsolete entries when removed.\n\nHeapsort\n\nHeapsort builds a max-heap, repeatedly exchanges the root with the last element in the active heap, and restores heap order after shrinking the active region. This produces an ascending sequence.\n\nThe method is a sorting algorithm with \\(O(n\\log n)\\) worst-case running time. Its conventional iterative implementation uses \\(O(1)\\) auxiliary space, but it is not stable: equal-key elements may change their relative order.\n\nSelection and merging\n\nA heap of size \\(k\\) can retain the \\(k\\) largest elements encountered in a stream. A min-heap exposes the smallest retained element, making it easy to decide whether a new element should replace it. Processing \\(n\\) elements takes \\(O(n\\log k)\\) time for \\(k\\geq 2\\) and \\(O(k)\\) storage.\n\nFor merging \\(k\\) sorted sequences, a min-heap can hold the next available element from each sequence. After extracting the smallest, the algorithm inserts its successor from the same sequence. For \\(N\\) total elements and \\(k\\geq 2\\), this gives \\(O(N\\log k)\\) time."
    },
    {
      "heading": "Limitations and implementation considerations",
      "text": "No efficient general search. Heap order is insufficient for binary search within the backing array. Ordered traversal and range queries are usually better supported by search trees.\n\nNo inherent stability. Equal-priority elements need not be removed in insertion order. A stable priority queue can compare a pair consisting of the priority and an insertion sequence number.\n\nMutable keys require repair. Changing a key externally without restoring heap order can invalidate subsequent operations. Interfaces may prohibit such mutation or require explicit update operations.\n\nComparison rules must be consistent. Correctness depends on a coherent ordering relation. Values such as floating-point NaN need explicit treatment when the language’s ordinary comparisons do not provide the required ordering.\n\nMerging is not especially efficient. Concatenating two heap arrays and rebuilding takes linear time in their combined size. This is useful for bulk merging but does not provide the efficient meld operations available in some other heap structures.\n\nArray positions are not stable identities. Insertions, removals, and repairs move elements. External references to positions require maintenance, and array reallocation may also invalidate direct memory references."
    },
    {
      "heading": "History and related structures",
      "text": "J. W. J. Williams introduced the binary heap in connection with heapsort in 1964. Floyd published an improved heapsort method in the same year, including the bottom-up construction technique that underlies standard linear-time build-heap procedures.\n\nA binary heap is a special case of a d-ary heap, in which each node can have up to \\(d\\) children. Larger branching factors reduce tree height but require examining more children during sift-down.\n\nOther priority-queue structures make different trade-offs. Binomial heaps support efficient merging, while Fibonacci heaps provide stronger amortized bounds for operations such as decrease-key. Binary heaps remain widely used because their array representation is compact, their algorithms are simple, and their practical overhead is relatively low.\n\nThe word heap also denotes a region used for dynamic memory allocation. That use is distinct from the binary-heap data structure; a memory allocator need not organize its storage as a binary heap."
    }
  ],
  "links": [
    "data-structure",
    "binary-tree",
    "priority-queue",
    "heapsort",
    "binary-search-tree",
    "array-data-structure",
    "cpu-cache",
    "pseudocode",
    "hash-table",
    "time-complexity",
    "call-stack",
    "abstract-data-type",
    "cpu-scheduling",
    "dijkstra-algorithm",
    "a-star-search",
    "sorting-algorithm",
    "binary-search",
    "not-a-number"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}