1. Heap
A binary heap is an array that can be seen as an approximate complete binary tree.
There are two types of binary heaps: the maximum heap and the smallest heap. In the maximum heap, the value of the parent node is always greater than or equal to the value of any one of the child nodes. Therefore, the largest element in the heap is placed in the root node, and in either subtree, the number of all nodes contained in the word count is not greater than the value of the child tree root node. The minimum heap is the value of the parent node that is always less than or equal to any of the child nodes.
In the heap sorting algorithm, we use the maximum heap. The minimum heap is typically used to construct a priority queue.
2. Heap Storage
Arrays are generally used to represent heaps. General position 0 does not need to store the element, that is, the storage area is a[1,..., Len]. So for a node. Its parent node is labeled 2/i, the left child's subscript is 2*i, and the right child's node is 2*i+1.
If you want to use a position labeled 0, the parent node's subscript is (i-1)/2. Its left and right sub-nodes are labeled 2*i+1 and 2*i+2.
The 0 location will not be used in this article.
3. Downward adjustment
The downward adjustment is to maintain the nature of the heap. Its input is the array a and subscript I. It first looks at whether the node is larger than the value of its left and right child nodes, and if not, the larger values in the left and right child nodes are exchanged. The next level of heap may be broken after swapping, and then the next level of heap is constructed using the above method until the node is the root of the child structure. Time Complexity of O (LGN)
1 voidAdjustdown (Elemtype a[],intKintheap_size) {2 intChild ;3Elemtype tmp =A[i];4 5 for(inti = k <<1; I <= heap_size; I *=2) {//filter down along a child node with a large key value6 if(I < heap_size && A[i +1] >A[i]) {7i++;8 }9 if(A[child] <tmp) {TenA[K] = A[child];//Adjust A[child] to the parent's position OneK = i;//Modify key values so that you continue to filter down A}Else { - Break; - } the - } - -A[K] = tmp;//the filtered value is placed in the final position +}
The recursive method given in the introduction of the algorithm:
1InlineintLeft (inti) {2 returnI <<1;3 }4 5InlineintRight (inti) {6 returnI <<1+1;7 }8 9 voidAdjustdown (intA[],intKintheap_size) {Ten intLeft_child =Left (k); One intRight_child =Right (k); A - intlargest =K; - the if(Left_child <= heap_size && A[left_child] >A[largest]) { -largest =Leftc_child; - } - if(Right_child <= heap_size && A[right_child] >A[largest]) { +largest =Right_child; - } + A if(Largest! =k) { at swap (A[k], a[largest]); - Adjustdown (A, largest, heap_size); -}
4. Build a heap
can use
Heap and Heap sort