HEAPSORT (selection sort)

1 reactor concepts

Stack is a sequence storage of the complete binary tree .

Wherein each keyword node are not greater than the keyword of its children nodes, so called heap rootlets stack .

Wherein each node of the keywords are not less than a keyword which the child nodes, so called heap large root stack .

For example, for a sequence of n elements {R0, R1, ..., Rn} is satisfied if and only if one of the following relationship, known as the stack:

  (1) Ri <= R2i +  1 and Ri <= R2i + 2 ( small heap root)

  (2) Ri> = R2i +  1 and Ri> = R2i + 2 ( large root stack)

Where i = 1,2, ..., n / 2 rounded down; 

 

 

As shown above, the sequence R {3, 8, 15, 31, 25} is a typical small heap root.

There are two parent node heap, elements 3 and 8 elements.

3 element in the array to R [0] indicates, it is the left child node R [1], is the right child node R [2].

8 elements in the array to R [1] indicates that its left child node is R [3], is a right child node R [4], which is the parent node of R [0]. As can be seen, they satisfy the following rules :

Set to the current element in the array R [i] represents, then,

(1) its left child node is: R & lt [2 * I + 1] ;

(2) its right child nodes are: R & lt [* I 2 + 2] ;

(3) its parent node is: R & lt [(. 1-I) / 2] ;

(4) R[i] <= R[2*i+1] 且 R[i] <= R[2i+2]。

 

2 Key

First, a definition of the stack array R [0..n] adjusted stack (a process called to create the initial stack) , exchanging R [0] and R [n];

Then, the R [0..n-1] was adjusted to stack exchange R [0] and R [n-1];

Repeated until exchanged R [0] and R [1] up.

 

The above ideas can be summarized into two operations:

(1) According to the initial array configuration initial heap (construct a complete binary tree, the parent node to ensure that all its children nodes than the large value).

(2) each switching element of the first and last, output of the last element (maximum), and the remaining element to readjust a large heap root. 

After completion of output of the last element of the array has been arranged in the order from small to large.

First detailed look at the example of FIG, how to build the initial heap.

With a random sequence of {1, 3, 4, 5, 2, 6, 9, 7, 8, 0}.

 

After the initial construction of the heap, we look at the complete heap sort process:

Or for the aforementioned random sequence {1, 3, 4, 5, 2, 6, 9, 7, 8, 0} to be described.

 

Guess you like

Origin www.cnblogs.com/carpeak/p/11619849.html