Basic heap sorting process:
1. Find the largest element and put it to the end.
2. Find the second largest element and put it in the second-to-last position.
... And so on until all elements are sorted.
In each step, the method for finding the maximum element is to use the heap. Heap can be regarded as a Complete Binary Tree, and the value of each node is greater than the value of its subnode. For an array, any [I] element is greater than [2I + 1] and [2I + 2. In order to change unordered arrays into heaps, heap needs to be created from the leaf to the root. That is, the heap is established from the first node with a subnode to the root node. This sequence is selected because it ensures that the left and right subtree of each node is already heap. After the first heap is created, the first element is the maximum value, and it is swapped with the last element to complete the first step of sorting.
In this case, the last element in the array is the maximum value. In the first n-1 elements, the left and right subtree of the root node are all heap, and only the root element does not meet the heap conditions. You only need to adjust the maximum heap of the root node once. The first n-1 elements will be built into a new heap, and the second largest element is located in the root. Exchange with the second to last element to complete the second step of the process.
And so on to complete the sorting process.
// Adjust heap for array that begin at array, and length = nLen.// The left subtree and right subtree are already heap.void MaxHeapify(int array[], size_t nLen){int idxLarge = 0;int nTemp = array[0];for (int i=0; 2*i+1<nLen; i=idxLarge){int idxLeft = 2*i+1;int idxRight = idxLeft+1;if (array[idxLeft]>nTemp)idxLarge = idxLeft;if (idxRight < nLen && array[idxRight]>array[idxLarge])idxLarge = idxRight;if (idxLarge != i)array[i] = array[idxLarge];elsebreak;}array[idxLarge] = nTemp;}void HeapSort(int array[], size_t nLength){// BuildMaxHeapfor (int idx=nLength/2 - 1; idx>=0; idx--){MaxHeapify(array+idx, nLength-idx);}// swap root of heap with the last element, and re-adjust heap.for (int i=nLength-1; i>=1; i--){int nTemp = array[0];array[0] = array[i];array[i] = nTemp;MaxHeapify(array, i);}}