【資料結構--Heap】堆
阿新 • • 發佈:2018-11-13
堆(英語:Heap)是電腦科學中的一種特別的樹狀資料結構。若是滿足以下特性,即可稱為堆:“給定堆中任意節點 P 和 C,若 P 是 C 的母節點,那麼 P 的值會小於等於(或大於等於) C 的值”。若母節點的值恆小於等於子節點的值,此堆稱為最小堆(英語:min heap);反之,若母節點的值恆大於等於子節點的值,此堆稱為最大堆(英語:max heap)。在堆中最頂端的那一個節點,稱作根節點(英語:root node),根節點本身沒有母節點(英語:parent node)。
性質
- 任意節點小於(或大於)它的所有後裔,最小元(或最大元)在堆的根上(堆序性
- 堆總是一棵完全樹。即除了最底層,其他層的節點都被元素填滿,且最底層儘可能地從左到右填入。
Comparison of theoretic bounds for variants
根據上圖可以看出斐波那契堆和嚴格-斐波那契堆的效率比較高。
應用
The heap data structure has many applications.
- Heapsort: One of the best sorting methods being in-place and with no quadratic worst-case scenarios.
- Selection algorithms: A heap allows access to the min or max element in constant time, and other selections (such as median or kth-element) can be done in sub-linear time on data that is in a heap.[17]
- Graph algorithms: By using heaps as internal traversal data structures, run time will be reduced by polynomial order. Examples of such problems are
Prim's minimal-spanning-tree algorithm and Dijkstra's shortest-path algorithm.- Priority Queue: A priority queue is an abstract concept like "a list" or "a map"; just as a list can be implemented with a linked list or an array, a priority queue can be implemented with a heap or a variety of other methods.
- K-way merge: A heap data structure is useful to merge many already-sorted input streams into a single sorted output stream. Examples of the need for merging include external sorting and streaming results from distributed data such as a log structured merge tree. The inner loop is obtaining the min element, replacing with the next element for the corresponding input stream, then doing a sift-down heap operation. (Alternatively the replace function.) (Using extract-max and insert functions of a priority queue are much less efficient.)
- Order statistics: The Heap data structure can be used to efficiently find the kth smallest (or largest) element in an array.
1.堆(通常是二叉堆)常用於排序。這種演算法稱作堆排序。
2.優先順序佇列可以用堆實現。