#include
using namespace STD; Class heapsort {PRIVATE: int Len; vector
list; void swapnode (int I, int heapsize); Public: void sort (); void print (); heapsort (void );~ Heapsort (void) ;};
# Include <iostream> # include "heapsort. H" using namespace STD; heapsort: heapsort (void) {Len = 10;} heapsort ::~ Heapsort (void) {} void heapsort: swapnode (int I, int heapsize) {int L = I * 2; int r = I * 2 + 1; int max = I; if (L <= heapsize & list [L-1]> list [I-1]) max = L; If (r <= heapsize & list [r-1]> list [L-1]) max = r; If (max! = I) {int TMP = list [max-1]; list [max-1] = list [I-1]; list [I-1] = TMP; swapnode (max, heapsize );}} void heapsort: Sort () {for (INT I = Len/2; I> 0; I --) {swapnode (I, Len);} int heapsize = Len; for (INT I = len-1; I> 0; I --) {int TMP = list [I]; list [I] = list [0]; list [0] = TMP; swapnode (1, -- heapsize) ;}} void heapsort: Print () {for (INT I = 0; I <Len; I ++) {int RND = rand () % 100; List. push_back (RND); cout <RND <"" ;}cout <Endl; sort (); For (INT I = 0; I <Len; I ++) {cout <list [I] <";}cout <Endl ;}
By default, heap sorting regards arrays as a binary tree. The first step is to adjust the order of arrays from small to large from top to bottom (maximum heap ),
Step 2: extract the last number in the heap (tree), place the number on the heap top, and take out the maximum number on the heap top. Change the number of heap elements (the number has been removed) and adjust the smaller number on the top of the heap.
Step 2 clearly shows a lot of meaningless comparisons. In general, the heap sorting performance is not high, and the lowest complexity is nlogn.