When I first learned heap sorting, I thought it was a big scourge, but when I actually went to learn, the principle of heap sorting is actually very simple, that is, after a heap is built, take the root node (because the root node in the big top heap/small top heap is the largest /small), and then build a heap for the remaining elements, repeat the above process, continuously take out the remaining nodes of the root node and build a heap, until finally when all the nodes are taken out, it becomes orderly.
/*********** 堆排序 ***********/
void Swap(double &arr1, double &arr2)
{
double temp = arr1;
arr1 = arr2;
arr2 = temp;
}
// 调整堆
int HeapAdjust(double *arr, int dad,int m)
{
for (int son = 2 * dad + 1; son < m; son = 2 * dad + 1)
{
if (son + 1 < m && arr[son] < arr[son + 1])
++son;
if (arr[dad] > arr[son])
return 0;
Swap(arr[dad], arr[son]);
dad = son;
}
return 0;
}
// 堆排序
int HeapSort(double *arr, int arrLenth)
{
for (int i = arrLenth/2-1 ; i >=0 ; i--)
HeapAdjust(arr, i, arrLenth); // 建堆
for (int i = arrLenth-1 ; i >=1 ; i--)
{
Swap(arr[0], arr[i]);
HeapAdjust(arr, 0, i - 1);
}
return 0;
}
Note: Be sure to pay attention to the boundary conditions of the for loop, and do not cross the boundary of the array.