Classic sorting algorithm-heap sort heap sorts
The heap sort is a little complex, divided into three pieces.
The first block, what is the heap, what is the maximum heap
The second block, how to adjust the heap to the maximum heap, this part is the focus
Third piece, heap sort introduction
The first block, what is the heap, what is the maximum heap
What is a heap
Here the heap (binary heap), refers to not the stack of the heap, but a data structure.
The heap can be regarded as a complete two-fork tree, and an "excellent" property of a complete binary tree is that each layer is full except the bottommost, which allows the heap to be represented by an array, with each node corresponding to an element in the array.
The relationship between the array and the heap
Binary heaps are generally divided into two types: maximum heap and minimum heap.
What is the maximum heap
The element value of each parent node in the heap is greater than or equal to its child node (if present), so the heap is a maximum heap
Therefore, the largest element value in the maximum heap appears at the root node (heap top).
Relationship between node and array index
For a given node subscript I, it is easy to calculate the parent node of the node, the child node subscript, and the calculation formula is very beautiful and simple
The second block, how to adjust the heap to the maximum heap, this part is the focus
The whole process is as shown
In this small heap of 4,14,7, the parent node 4 is smaller than the left child 14, so the two exchange
In 4,2,8 this small heap inside, the parent node 4 small less right operand child 8, so the two exchange
Shows the process of adjustment, which is implemented recursively until the maximum heap is adjusted.
Third piece, heap sort introduction
The heap sort is to take the maximum number out of the top of the heap,
The remaining heap continues to be adjusted to the maximum heap, and the process is introduced in the second block, which is implemented recursively
After the remainder is adjusted to the maximum heap, the maximum number of heap tops is removed again, the remainder is adjusted to the maximum heap, and the process lasts until the remaining number is only one end
The bottom three graphs describe the whole process in detail
Reference articles
Http://blog.kingsamchen.com/archives/547#viewSource
Classic sorting algorithm-heap sort heap sorts