Classic sorting algorithm-heap sorting Heap Sort
Heap sorting is a little complicated and divided into three parts.
First, what is heap and what is the largest heap
The second part focuses on how to adjust the heap to the largest heap
Section 3: heap sorting
First, what is heap and what is the largest heap
What is heap?
The Heap here is not the heap of the stack, but a data structure.
A heap can be regarded as a complete binary tree. The "excellent" nature of a Complete Binary Tree is that, except for the bottom layer, each layer is full, which allows the heap to be represented by arrays, each node corresponds to an element in the array.
Relationship between arrays and heaps
Binary heap is generally divided into two types: Maximum heap and minimum heap.
What is the largest heap?
Element values of each parent node in the heapGreater than or equalIts child node (if any), such a heap is the largest heap.
Therefore, the maximum element value in the maximum heap appears at the root node (heap top)
Relationship between nodes and array Indexes
For the subscript I of a given node, it is easy to calculate the subscript of the parent node and child node of the node, and the formula is very beautiful and simple.
The second part focuses on how to adjust the heap to the largest heap
Shows the entire process.
In the heap 4, 14, 7, the parent node 4 is less than the left child 14, so the two exchange
In the heap of 4, 2, 8, the parent node 4 is less than the right child 8, so the two exchange
Shows the adjustment process, which is implemented recursively until it is adjusted to the maximum heap.
Section 3: heap sorting
Heap sorting is to extract the maximum number of heap tops,
Change the remaining heap to the largest heap. The specific process is described in the second part, which is implemented recursively.
After the remaining part is adjusted to the maximum heap, the maximum number of heap top is retrieved again, and the remaining part is adjusted to the maximum heap. This process continues until there is only one remaining part.
The following three figures describe the entire process in detail.
References
Http://blog.kingsamchen.com/archives/547#viewSource
Back to main directory [classic Sorting Algorithm] [Collection]