Sort the heap, use a large heap to achieve ascending, small heap to achieve descending. For example, in ascending order, the larger data is stored on the last side, and the data is stored sequentially. In exchange for the first and last elements, the heap without the last element is lowered, the heap remains large, the largest data is stored in the first position in the heap, and the above steps are cycled until the number of data to be lowered is 0.
Void adjustdown (int *a, size_t root, size_t size)//downward--k an array subscript, size number of elements {// Large heap of Size_t parent = root;size_t child = parent * 2 + 1;while (child < size) {if (child + 1 < size && a[ Child] < a[child + 1]) {++child;} if (A[parent] < a[child]) {swap (A[parent], a[child]);p Arent = child;child = parent * 2 + 1;} else//Notice that the interchange condition is not met when you jump out of this loop {break;}}} Void heapsort (int *a, size_t size)//heap sort--take a quick sort (using a large heap to achieve ascending, small heap implementation descending) {assert (a);for (int i = ((int) size-2)/2; i >= 0; --i)//Build Heap {Adjustdown (a, i, size) //Downgrade I to heap top heap}for (size_t i = 0; i < size; ++i) {//Because the heap is a large heap, Then the first element and the last element are exchanged, then the swap (A[0], a[size - 1 - i]);//Exchange heap top data and last data, so that the last element holds the maximum (small) number/ /size-1-i for the nextAdjust the number of elements, each exchange minus 1, so that the last element does not participate in the downward adjustment, the heap top storage size-1-i number of the largest (small) Adjustdown (a, 0, size - 1 - i);}}
The test cases are as follows:
void Test () {//heap sort int arr[] = {Ten, A, a, a, a, a, a, a, a, a};size_t size = sizeof (arr)/sizeof (arr[0]); Heapsort (arr, size); for (size_t i = 0; i < size; ++i) {cout << arr[i] << "";} cout << Endl;}
This article is from the "Scen" blog, make sure to keep this source http://10741357.blog.51cto.com/10731357/1769544
Heap sorting--using a quick sort (using a large heap to achieve ascending, small heap implementation descending)