Steps for heap sort:
- Construct the array into a large root heap, at this time the top element of the heap is the largest element in the array
- Exchange the top element of the heap with the end element, and the maximum value of the array has been obtained at this time
- Repeat steps 1 and 2 for the remaining n-1 elements, and finally get an ordered array.
Heap sort implementation code:
/// <summary>
/// 堆排序
/// </summary>
/// <param name="nums"></param>
static void SortByHeap(int[] nums)
{
//构造大根堆 从最后一个非叶子节点开始
int len = nums.Length;
for (int i = len / 2 - 1; i >= 0; i--)
{
AdjustHeap(nums, i, len);
}
//调整堆
for (int i = len - 1; i > 0; i--)
{
//交换堆顶元素与末尾元素,得到当前i+1长度中的最大值
(nums[0], nums[i]) = (nums[i], nums[0]);
//剩余的i长度的元素继续构造大根堆
AdjustHeap(nums, 0, i);
}
}
/// <summary>
/// 调整堆
/// </summary>
/// <param name="nums"></param>
/// <param name="begin">开始下标</param>
/// <param name="length">调整长度</param>
static void AdjustHeap(int[] nums, int begin, int length)
{
int temp = nums[begin];
for (int i = 2 * begin + 1; i < length; i = 2 * i + 1)
{
if (i + 1 < length && nums[i + 1] > nums[i]) i++;
if (nums[i] > temp)
{
nums[begin] = nums[i];
begin = i;
}
else
{
break;
}
}
nums[begin] = temp;
}