堆数据结构有很多应用。
- 堆排序:最好的排序方法之一是就地排序并且没有二次最坏情况。
- 选择算法:可以使用堆在线性时间(通常是恒定时间)内找到最小值、最大值、最小值和最大值、中值甚至第 k 个最大元素。 [4]
- 图算法:通过使用堆作为内部遍历数据结构,运行时间将通过多项式顺序减少。此类问题的示例是 Prim 的最小生成树算法和 Dijkstra 的最短路径问题。
Full and almost full binary heaps may be represented in a very space-efficient way using an array alone. The first (or last) element will contain the root. The next two elements of the array contain its children. The next four contain the four children of the two child nodes, etc. Thus the children of the node at position n would be at positions 2n and 2n+1 in a one-based array, or 2n+1 and 2n+2 in a zero-based array. This allows moving up or down the tree by doing simple index computations. Balancing a heap is done by swapping elements which are out of order. As we can build a heap from an array without requiring extra memory (for the nodes, for example), heapsort can be used to sort an array in-place.
One more advantage of heaps over trees in some applications is that construction of heaps can be done in linear time using Tarjan's algorithm.
Reference: http://en.wikipedia.org/wiki/Heap_%28data_structure%29