Sorting Algorithm-heap sorting
The heap sorting algorithm is based on the data structure like heap. In fact, heap listening is very high-end. It is actually very simple. It is a binary tree, but it has special conditions, that is, the heap whose parent node is larger (or smaller) than the child node is called the maximum heap (minimum heap). It instantly feels very simple. The simplest way to save it is to store it directly using arrays.
Given a set of numbers, we need to build a heap before using heap sorting. However, the number of groups must not satisfy the nature of the above heap, so we need to adjust it, how can I adjust it to satisfy the heap nature and turn it into a heap? Taking the largest heap as an example, for a node, we can determine whether the child is bigger than Father's Day. If yes, we can exchange the two values so that the father is bigger than the child, of course, after the switch is complete, the Child tree with the child as the root node may not satisfy the nature of the child, and the switch continues until all are satisfied. In order to reduce the number of exchanges, we can switch from the node closest to the leaf node, one layer to the root node.
For example, if the number of such a group is a [] = {16, 7, 3, 20, 17,8}, we create a heap.
Then adjust
So a heap is built up. The rest is simple.
With the heap, we can easily find that the heap has a nice property, that is, the value of the root node is locked and all values are large (small). Then we select the root node for the first time, put n-I + 1 in the array, then place the value of n-I + 1 in the root node, and adjust the heap. After n times, it is ordered. Procedure 1
Release/release + zcrH08XPyLbTwdCjrMv50tS087zSv8nS1L + 0 s/release + y5cjr0ru49tSqy9jKx0 + release/release "brush: java;"># Include # Include # Include Using namespace std; const int n= 1001000; int a [N]; void Balance (int x, int N) {int l = x + x; int r = x + 1; int mid = x; if (l A [mid]) mid = l; if (r A [mid]) mid = r; if (x! = Mid) {swap (a [x], a [mid]); Balance (mid, n) ;}} void Heap_Sort (int n) {for (int I = n/2-1; I> = 0; I --) // first adjust the heap Balance (I, n); for (int I = n-1; I >= 0; I --) {swap (a [I], a [0]); Balance (0, I) ;}} int main () {// freopen ("Input.txt", "r", stdin); int n, k; while (~ Scanf ("% d", & n, & k) {for (int I = 0; I