Heap: Heap is a complete binary tree, the value of a node in the heap is always not greater than or not less than the value of its parent node;
Maximum heap (big root heap): the heap with the largest root node;
Minimal heap (small root heap): the heap with the smallest root node;
If a one-dimensional array is regarded as a complete binary tree stored sequentially, it has the following relationship:
For any parent node, assuming its subscript is x, the left child (if any) is subscript (2x + 1), and the right child (if any) is subscript (2x + 2).
Heap sort: a selection sort. Adjust the array with n elements into a heap (largest heap or smallest heap), take out the top element of the heap (placed at the beginning or end of the array), then re-adjust the remaining n-1 elements to a heap, and take out the heap again The top element, and so on, finally get a sorted array.
Ideas
The example in this article is to build the largest pile, arranged in ascending order.
The idea is as follows: (the array is a, the number of elements is n)
Adjust the array a to the maximum heap, then a[0] is the top element (maximum);
Put the top element a[0] of the heap at the end of the array (a[0] is exchanged with a[n -1]);
Re-adjust the first n-1 elements to a heap (actually only a[0] may not satisfy the maximum heap at this time);
Put the top element a[0] of the heap at the second end of the array (a[0] and a[n -2] swap);
By analogy, the final array is arranged in ascending order;
In summary, there are actually only two problems that need to be solved:
1 How to adjust the complete binary tree represented by the array to a heap?
2 How to adjust a group of elements whose root node does not satisfy the heap into a heap?