Heap sort explanation and code (C ++)
Two steps are involved in heap sorting.:
Step 1:YesDading heap(Sorted in ascending order) orSmall top heap(Sorting from small to large ),Create from bottom up; For example, when a heap is created, s is from large to small;
Step 2:YesExchangeHeap top and heap bottom, andHeap bottom output after switching, Only arrange the remaining heap,Create from top down; For example, s is always 1 during construction;
Heap Sort)OfTime ComplexityYesO (nlogn),Worst caseThis is also true.
WhileQuick Sort)If the initial record sequence is ordered, the quick sorting degradesBubble Sort)The time complexity isO (n ^ 2).
This is a heap sorting method than quick sorting.Advantages.
Code:
/** Main. cpp ** Created on: 2014.6.12 * Author: Spike * // * eclipse cdt, gcc 4.8.1 */# include
# Include
# Include
Using namespace std; void HeapAdjust (std: vector
& L, int s, int num) {int temp = L [s-1]; for (int j = 2 * s; j <= num; j * = 2) {if (j
L [j]) // select the smallest node position + + j; if (temp <L [J-1]) // do not exchange break; L [s-1] = L [J-1]; // exchange value s = j; // continue searching} L [s-1] = temp;} void HeapSort (std: vector
& L) {int num = L. size (); for (int I = num/2; I> 0; -- I) {HeapAdjust (L, I, num ); // build heap from Layer 2} for (int I = num; I> 1; -- I) {std: swap (L [0], L [I-1]); heapAdjust (L, 1, I-1); // build heap from vertex, ignore last} return;} int main (void) {std: vector
L = {49, 38, 65, 97, 76, 13, 27, 49}; HeapSort (L); for (std: size_t I = 0; I
Output:
97 76 65 49 49 38 27 13