Heap Sort (heap sort) specific explanation and code (c + +)
This address: Http://blog.csdn.net/caroline_wendy
heap sequencing consists of two steps :
The first step is to build a large top heap (from large to small sort) or a small top heap (from smallest to largest), and build from the bottom up; When building a heap, S is from large to small;
The second step is to swap the top of the heap and the bottom of the heap, and then output the bottom of the exchange, just arrange the remaining piles, and build from the top down ; When constructed, S is always 1;
The time complexity of the heap sort ( heap sort) is O (NLOGN), which is the worst case scenario.
High-speed sequencing (Quick sort), if the initial sequence of records, high-speed sequencing will degenerate into a bubble sort (Bubble sort), the time complexity is O (n^2).
This is the forte of heap sorting than high-speed sequencing.
Code:
/* * main.cpp * * Created on:2014.6.12 * author:spike *//*eclipse CDT, gcc 4.8.1*/#include <iostream> #includ E <stack> #include <queue>using namespace std;void heapadjust (int data[], int length, int k) {int tmp = Data[k] ; int I=2*k+1;while (i<length) {if (i+1<length && data[i]>data[i+1])//Select Minimum node location ++i;if (tmp < data[i] )//without exchange break;data[k] = Data[i]; Exchange value k = i; Continue to find i = 2*k+1;} DATA[K] = tmp;} void heapsort (int data[], int length) {if (data = = NULL | | length <= 0) return;for (int i=length/2-1; i>=0;-I.) {HEA Padjust (data, length, i); Build the heap}for (int i=length-1; i>=0;-i) from the second level {Std::swap (data[0], data[i]); Heapadjust (data, I, 0); Build the heap from the vertex, ignoring the last}return;} int main (void) {int data[] = {$, a, a, N, a, 49};int, a, and a length = 8; Heapsort (data, length), for (int i=0; i<length; ++i) {std::cout << data[i] << "";} Std::cout << Std::endl;return 0;}
Output:
Data structure-heap sorting (heap sort) specific explanations and codes (C + +)