Start with a C + + code to see the process of push sequencing:
1#include <iostream>2#include <algorithm>3 using namespacestd;4 5 BOOLcmpConst intLhsConst intRHS)6 {7 returnLHS >RHS;8 }9 Ten intMain () One { A intArr[] = {4,2,Ten,9,5,6,8,6,7,1,3}; -Make_heap (arr, arr+Ten); - for(inti = One; I >=0; --i) { thePop_heap (arr, arr+i); - for(inti =0; I < One; ++i) cout << Arr[i] <<' '; -cout <<Endl; - } + - return 0; +}
Mainly Make_heap, pop_heap
Make_heap: Build heap, default Max heap-"Get increment array (because POP_HEAP is to take the heap top out and then put it back)
Pop_heap:arr[0] and Arr[i] exchange, and maintain the heap structure of arr[0] to arr[i-1].
Meke_heap can be subdivided into a heap from the bottom to the top, the recursive is to maintain I, you have to maintain the i.left and i.right.
And Pop_heap is the N-Times maintenance root node.
So, in fact, just write a maxheapify.
1 voidMaxheapify (intArr[],intNinti)2 {3 intL =2*i;4 intR =2*i +1;5 intlargest = i;6 if(L < n && Arr[l] >Arr[largest])7largest =L9 if(R < n && Arr[r] >Arr[largest])Tenlargest =R; One A if(Largest = = i)return; - swap (Arr[i], arr[largest]); - maxheapify (arr, n, largest); the}
The process of maintaining the heap is simply to keep sinking.
The back of the Meke_heap and pop_heap is not difficult to write.
Makeheap (arr, n):
For i = N/2 Downto 1:
Maxheap (arr, n, i);
Popheap (arr, n):
Swap (arr[0], arr[--n]);
Maxheap (arr, n, 0);
Then the sortHeap is easy to write:
SortHeap (arr, n):
Makeheap (arr, n);
For i = n Downto 0:
Popheap (arr, i);
sorting | Heap Sort