The heap sort contains two steps:
The first step: is to establish a large top heap (from large to small sort) or a small top heap (from little to large sort), from the bottom up; When the heap is built, S is from large to small;
The second step: is to switch the pile top and bottom, and the exchange of the bottom of the heap output, only arrange the remaining heap, from the top down to build; When constructed, S is always 1;
The time complexity of the heap sort (Heap sort) is O (Nlogn) and, at worst, the case.
And quick Sort, if the initial sequence of records is ordered, the quick sort will degenerate to bubble sort (Bubble sort), and the time complexity is O (n^2).
This is the advantage of heap sorting over a quick sort.
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
Code:
* * * main.cpp * * Created on:2014.6.12 * author:spike//*eclipse CDT, gcc 4.8.1*/#incl
Ude <iostream> #include <stack> #include <queue> using namespace std;
void Heapadjust (std::vector<int>& L, int s, int num) {int temp = l[s-1];
for (int j=2*s; j<=num; j*=2) {if (J<num && l[j-1] > L[j])//Select the smallest node location ++j;
if (temp < l[j-1])//Do not exchange break; L[S-1] = l[j-1]; Exchange value s = j;
Continue to find} l[s-1] = temp;
} void Heapsort (std::vector<int>& L) {int num = l.size (); for (int i=num/2; i>0;-i) {heapadjust (L, I, num);//Build Heap from second layer} for (int i=num; i>1;
-i) {Std::swap (l[0], l[i-1]); Heapadjust (L, 1, i-1);
Build the heap from the vertex, ignoring the last} return; int main (void) {std::vector<int> L ={49, 38, 65, 97, 76, 13, 27, 49};
Heapsort (L);
For (std::size_t i=0 i<l.size (); ++i) {std::cout << l[i] << "";
} std::cout << Std::endl;
return 0; }
Output:
97 76 65 49 49 38 27 13