Four, (1) heap sorting
The first time to listen to heap sorting is in 107lab listen to brother, but did not say how to achieve. At that time just looked at the data structure of the two-tree, but also thought to be through the pointer to establish a two-tree way to achieve, feel very difficult.
In fact, the heap sort implementation is not as difficult as it might seem.
The word "heap" was originally proposed in the heap sort, but later gradually referred to the "Scrap collection Storage Area", as in programming language Lisp and the facilities provided in Java. The heap data structures we have here are not scrap collection storage areas.
The runtime of the heap sort is the same as the merge sort o (n lg N), but a sort in situ (in place).
(binary) The heap data structure is an array object that can be considered as a complete binary tree.
The storage data structure for an array arr[]={16,14,10,8,7,9,3,2,4,1} is shown in the following illustration:
In this structure, for each root node I, make sure it's bigger than his sub node.
We can use an array a "1...length" a "" to represent this complete binary tree structure. Where a "1" is the root node 1
The first problem is to find the coordinates of the parent node, the left son, and the right son, by observing that we can use a macro or inline function:
According to a node subscript I, calculate the parent section
, the left son, the right son's subscript
inline int Parent (int i) {return i>>1;}
inline int Left (int i) {return i<<1;}
inline int Right (int i) {return (i<<1) |1}//bitwise operation multiplied by 2, the result is even so the last one must be 0,
so |1 will turn the last one to 1, so as to achieve the effect of adding 1
Whether it is "C + + primer" or "effective C + +", have talked about the shortcomings of macros, with the inline function is a better choice. Bit operations do multiplication and division faster.
As for the algorithm demo process in the "introduction of Algorithms" said very detailed, no longer repeat.
The heap sort process requires the following three functions:
1, Max-heapify (a,i): Keep the nature of the heap, let A "I" in the largest heap "descent", so that the number of I-node as the root of the tree