排序算法——堆排序(Heap Sort)
堆(Heap)
Heap is a complete binary tree which satisfies the heap condition:
Each child has a key which is no greater than its parent’s.
There are some trees, which are heaps? which are non-heaps?
(There is power tool to draw Heap or other structure tree https://visualgo.net/en)
(a) is a heap.
(b) is not a heap as it is not a complete binary tree.
(c) is a heap. Please note that heap allows such nodes with identical key.
(d) is not a heap. 31 as a child is greater than its parent 26.
(e) is a heap.
Generally, we say a tree as a heap. Heap represents max-heap by default. On there other hand, we can have a min-heap in which each child is no smaller than its parent.
堆的数组表示(Heap as array)
We place its elements in level-order in an array H.
Assume the parent of X is a node of infinite key. Place it in H[0]. This is just for easily understanding. It actually does not exist.
堆的属性(Properties of heap)
1. H[i] has a parent H[i/2]. (1 ≤ i ≤ n)
2. H[i] ≤ H[i/2].
3. The root of the tree H[1] has the maximum key.
4. Each subtree is still a heap.
5. The nodes which are parents are in array positions 1 to ⌊n/2⌋. Why? because the last node is in position n. Its parent is in position ⌊n/2⌋. Obviously, nodes before n/2 are all parents.
6. The height of heap is ⌊log2 n⌋. Why? we assume that the tree has a height h and the number of nodes n. The number of nodes at lowest level is between 1 and 2^h. n is between
⌊X⌋ means get the integer part of X. For example,
Hence, h=⌊log2 n⌋.
堆的操作(Operations on heap)
1. Inject a new node.