{
  "id": "priority-queue",
  "title": "Priority Queue",
  "lang": "en",
  "source_lang": "en",
  "summary": "A priority queue is an abstract data type that retrieves elements according to priority rather than insertion order, commonly implemented using a heap.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Priority queue ADT"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/priority-queue/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/priority-queue/",
      "json": "https://aiwiki.page/zh/priority-queue.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A priority queue is an abstract data type that stores elements with associated priorities and provides access to an element with the highest priority under a specified ordering. Unlike an ordinary queue, which normally removes elements in first-in, first-out order, a priority queue selects elements by priority. It is a fundamental component of graph algorithms, scheduling systems, and event-driven simulations. A priority queue describes an interface and its behavior; a heap is one possible implementation, not a synonym for the abstraction."
    },
    {
      "heading": "Ordering and basic operations",
      "text": "A priority queue usually takes one of two forms:\n\n- A min-priority queue returns an element with the smallest key.\n- A max-priority queue returns an element with the largest key.\n\nHere, a key is the value used to determine priority. The word “highest” therefore refers to precedence, not necessarily to the largest numerical value: a task with priority number 1 may precede a task with priority number 5.\n\nThe basic operations are:\n\nOperation | Meaning\ninsert(item, key) | Add an element with a specified priority\npeek() or find-min() / find-max() | Return a highest-priority element without removing it\nextract-min() / extract-max() | Remove and return a highest-priority element\nis-empty() | Test whether the queue contains any elements\nsize() | Return the number of stored elements\n\nSome interfaces also support changing an element’s priority, deleting a specified element, or melding two queues. In a min-priority queue, decrease-key improves an element’s priority; in a max-priority queue, increase-key does so.\n\nFor example, inserting the pairs \\((4,A)\\), \\((1,B)\\), and \\((3,C)\\) into a min-priority queue produces the extraction sequence \\(B,C,A\\), regardless of their insertion order.\n\nTies and stability\n\nPriority queues generally permit multiple elements with equal priorities. Their relative extraction order is unspecified unless the interface explicitly guarantees otherwise.\n\nA stable priority queue preserves insertion order among elements with equal priority. A common implementation assigns each insertion a monotonically increasing sequence number and compares the pair\n\n\\[(\\text{priority},\\text{sequence number})\\]\n\nlexicographically. In a min-priority queue, the earlier insertion then wins a tie. This technique also avoids comparing payload objects when equal priorities occur.\n\nThe comparison relation must behave consistently. Many implementations require a strict weak ordering, which allows equivalent keys while maintaining a coherent ordering. Inconsistent comparators, or special values such as floating-point NaN without an explicit ordering policy, can invalidate the structure’s assumptions."
    },
    {
      "heading": "Implementations and complexity",
      "text": "Different data structures implement the same priority-queue interface with different performance trade-offs. The most suitable representation depends on the frequency of insertions, extractions, priority changes, and melds.\n\nFor a min-priority queue containing \\(n\\) elements, representative time complexities are:\n\nRepresentation | Find minimum | Insert | Extract minimum\nUnsorted linked list | \\(O(n)\\) | \\(O(1)\\) | \\(O(n)\\)\nSorted linked list, minimum at head | \\(O(1)\\) | \\(O(n)\\) | \\(O(1)\\)\nBinary heap | \\(O(1)\\) | \\(O(\\log n)\\) | \\(O(\\log n)\\)\nBalanced binary search tree | \\(O(\\log n)\\), or \\(O(1)\\) with a cached minimum | \\(O(\\log n)\\) | \\(O(\\log n)\\)\nFibonacci heap | \\(O(1)\\) | \\(O(1)\\) amortized | \\(O(\\log n)\\) amortized\n\nThese bounds describe the principal data-structure operations. Dynamic memory allocation, array resizing, and user-defined comparisons can add costs.\n\nAn unsorted representation is useful when insertions dominate and minimum extraction is rare. A sorted representation reverses this trade-off. Balanced trees, such as a red–black tree, provide additional capabilities such as ordered traversal and range queries, but typically require more structural overhead than an array-based heap.\n\nBinary heaps\n\nA binary heap is a complete binary tree satisfying a heap-order property. In a min-heap, every parent’s key is no greater than its children’s keys. Consequently, the root contains a minimum element, although the remaining elements are not globally sorted.\n\nThe tree is commonly stored in an array. With zero-based indexing, the children of index \\(i\\) are at\n\n\\[2i+1 \\quad \\text{and} \\quad 2i+2,\\]\n\nwhen those positions exist. For \\(i>0\\), its parent is at\n\n\\[\\left\\lfloor \\frac{i-1}{2} \\right\\rfloor.\\]\n\nInsertion appends the new element and repeatedly exchanges it with its parent while heap order is violated. This is called sifting up.\n\nExtraction removes the root, moves the last element into its position, and restores heap order by sifting down, exchanging it with the smaller child as necessary. Both procedures follow a path whose length is at most proportional to the tree’s height, giving \\(O(\\log n)\\) time.\n\nAn existing array can be converted into a heap in \\(O(n)\\) time using bottom-up heap construction. This is faster than the \\(O(n\\log n)\\) worst-case cost of inserting its elements one at a time. The linear bound arises because most nodes are near the leaves and require little or no downward movement.\n\nBinary heaps use \\(O(n)\\) storage and have a compact layout that often benefits cache locality.\n\nOther heap families\n\nSeveral heap variants optimize different operations:\n\n- \\(d\\)-ary heaps give each node up to \\(d\\) children. Increasing \\(d\\) reduces height but increases the number of child comparisons during downward repair.\n- Binomial heaps organize elements into a collection of structured trees and support melding in \\(O(\\log n)\\) time.\n- Fibonacci heaps support insertion, melding, and decrease-key in \\(O(1)\\) amortized time, with \\(O(\\log n)\\) amortized minimum extraction.\n- Pairing heaps use comparatively simple tree-linking operations and are another option for meldable priority queues.\n\nAn amortized bound limits the average cost per operation over a sequence of operations; it is not a guarantee that each individual operation has that cost. Sophisticated asymptotic bounds also do not guarantee faster execution on every workload: allocation, pointer access, comparison cost, and implementation complexity matter."
    },
    {
      "heading": "Changing priorities and locating elements",
      "text": "Finding the minimum is efficient in a heap, but finding an arbitrary element is not. A binary heap alone may require \\(O(n)\\) time to locate a particular item.\n\nAn indexed priority queue maintains a mapping from element identifiers to heap positions. Whenever two heap entries are exchanged, the mapping is updated. Once an element’s position is known, changing its priority or deleting it takes \\(O(\\log n)\\) time in a binary heap. The mapping can use an array for a dense identifier space or a hash table for more general identifiers.\n\nAnother approach is lazy invalidation. Rather than updating an existing entry, the program inserts a new entry and marks the old one obsolete, or records the current version separately. Obsolete entries are discarded when encountered during extraction. This avoids a dedicated decrease-key operation but can increase memory consumption and the number of extractions.\n\nDirectly changing a stored element’s priority without notifying or repairing the queue can break heap order. Similarly, if priorities depend on time or other mutable external state, their relative order must remain valid or the structure must be updated."
    },
    {
      "heading": "Applications",
      "text": "Graph search and shortest paths\n\nDijkstra’s algorithm uses a min-priority queue to select the vertex with the smallest tentative distance. For a graph with \\(V\\) vertices and \\(E\\) edges, an adjacency-list implementation with an indexed binary heap takes\n\n\\[O((V+E)\\log V)\\]\n\ntime. With a Fibonacci heap, the corresponding bound is \\(O(E+V\\log V)\\). These bounds assume nonnegative edge weights, as required by Dijkstra’s algorithm.\n\nA* search prioritizes candidate states using an estimated total path cost, commonly written\n\n\\[f(n)=g(n)+h(n),\\]\n\nwhere \\(g(n)\\) is the known cost to reach a state and \\(h(n)\\) estimates the remaining cost.\n\nPriority queues also appear in minimum spanning tree algorithms and other procedures that repeatedly select the currently best candidate.\n\nScheduling and event processing\n\nIn CPU scheduling, ready tasks may be ordered by priority, deadline, or another scheduling key. A priority queue supplies the selection mechanism; it does not by itself define the scheduling policy.\n\nDiscrete-event simulations maintain a queue of future events ordered by simulated execution time. The simulator repeatedly extracts the earliest event, processes it, and inserts any newly generated events. Timer management and some event-loop implementations use a similar arrangement.\n\nStrict priority scheduling can cause starvation if higher-priority work continually arrives. Techniques such as priority aging change the scheduling policy to address this; fairness is not an inherent property of a priority queue.\n\nCompression, merging, and selection\n\nHuffman coding repeatedly removes the two lowest-weight nodes and inserts a node representing their combination.\n\nA priority queue can also merge \\(k\\) sorted sequences by maintaining the next available element from each sequence. For \\(N\\) total elements, this takes \\(O(N\\log k)\\) time, apart from input and output costs.\n\nTo retain the largest \\(k\\) elements of a stream, a min-heap of size at most \\(k\\) keeps the smallest retained element at its root. Each new candidate can then be rejected or used to replace that root in \\(O(\\log k)\\) time."
    },
    {
      "heading": "Relationship to sorting and queues",
      "text": "Repeatedly extracting the minimum from a priority queue produces elements in nondecreasing order. Heapsort exploits heap ordering to achieve \\(O(n\\log n)\\) worst-case running time.\n\nThe comparison-sorting lower bound also constrains priority queues. For arbitrary comparable keys, a queue cannot provide both insertion and extraction in constant amortized time for every input: inserting \\(n\\) items and extracting them all would otherwise yield a comparison-based sorting algorithm taking \\(O(n)\\) time.\n\nThis argument does not apply unchanged to restricted key domains. Small integer priorities can be handled with buckets, while specialized integer queues can exploit the representation of keys or restrictions on their order.\n\nAn ordinary queue or a stack can be modeled by assigning priorities based on arrival order. Their specialized implementations are generally simpler and provide stronger operation-specific efficiency."
    },
    {
      "heading": "Practical limitations and interface details",
      "text": "A priority queue guarantees access to an extreme element, not sorted iteration. Traversing a heap’s backing array usually reveals neither insertion order nor priority order.\n\nA standard binary heap also does not support especially efficient melding: concatenating two heap arrays and rebuilding takes time linear in their combined size. Applications that meld frequently may favor a meldable heap.\n\nFor concurrent computing, simultaneous insertions and extractions require coordination. Exact minimum extraction can become a contention point because many workers compete for the same end of the ordering. Some concurrent designs relax the requirement and return an element near the minimum, trading strict semantics for greater throughput.\n\nFinally, standard-library interfaces expose different capabilities. A library priority queue may support only insertion, inspection, and extraction even if its underlying structure could support additional operations. Stability, arbitrary deletion, priority updates, thread safety, and empty-queue behavior are properties of the particular interface rather than universal guarantees."
    }
  ],
  "links": [
    "abstract-data-type",
    "queue-data-type",
    "not-a-number",
    "data-structure",
    "time-complexity",
    "red-black-tree",
    "binary-heap",
    "binary-tree",
    "array-data-structure",
    "cpu-cache",
    "amortized-analysis",
    "hash-table",
    "dijkstra-algorithm",
    "a-star-search",
    "cpu-scheduling",
    "event-loop",
    "huffman-coding",
    "heapsort",
    "sorting-algorithm",
    "stack-data-type",
    "concurrent-computing"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}