Heap Structure: Any parent node is larger than its subnodes.
Logical Structure: Binary Tree
Physical Structure: Array
If it starts with the badge 0
Parent node left child node: 2 * I + 1
Parent node right child node: 2 * I + 2
Last non-leaf node: (n-1)/2
If you start with badge 1
Parent node left child node: 2 * I
Parent node right child node: 2 * I + 1
Last non-leaf node: n/2
Heap sorting analysis:
Optimal Time Complexity: O (nlog2n)
Worst time complexity: O (nlog2n)
Average time complexity: O (nlog2n)
Space complexity: O (1)
Stability: unstable
Heap sorting mainly consists of three functions:
1. Adjust the heapadjust (int * a, int I, int size) of the heap structure );
2. Build the heap void buildheap (int * a, int size );
3 heap sorting void heapsort (int * a, int size );
When the badge is 0, the heap sorting code is as follows:
// Adjust Heid heapadjust (int * a, int I, int size) {int lchild = 2 * I + 1; // left child node int rchild = 2 * I + 2; int max = I; // Temporary Variable // startnode-> (size-1)/2: last non-leaf node // select a child node greater than the parent node to exchange with the parent node // find the previous non-leaf node if (I <= (size-1)/2) // non-leaf node {If (lchild <= size & A [lchild]> A [Max]) {max = lchild ;} if (rchild <= size & A [rchild]> A [Max]) {max = rchild;} If (max! = I) {swap (& A [I], & A [Max]); heapadjust (A, Max, size ); // avoid having to adjust the child tree with Max as the parent node instead of a heap (downward adjustment for short }}}
// Build heap void buildheap (int * a, int size) {int I; // from the last non-leaf node :( size-1)/2 to the root node: 0 traverse forward (I = (size-1)/2; I> = 0; I --) {heapadjust (A, I, size );}}
// Heid heapsort (int * a, int size) {int I; buildheap (A, size); // build heap for (I = size; I> = 0; I --) {swap (& A [0], & A [I]); heapadjust (A, 0, I-1); // reset the heap node to a large top heap, place the maximum value at the end of the heap each cycle, and then rebuild size: heap of the I-1 }}
// Switch void swap (int * a, int * B) {int temp = * A; * A = * B; * B = temp ;}