堆排序(HeapSort)
动图显示:
- 将数组当作二叉树来进行处理
- 将二叉树构造成大顶堆(根节点的值大于或等于左右子树的值)或小顶堆(根节点的值小于或等于左右子树的值)
- 将二叉树的头结点和树的最末端交换(此时数组末尾是最大值),然后对剩下的length-1个数再进行构造大顶堆操作再将树的头结点和树的末端交换。。。(依次进行下去)
using System;
namespace cchoop
{
class Program
{
public static void Main()
{
int[] arr = { 50, 10, 90, 30, 70, 40, 80, 60, 100 };
HeapSort(arr);
foreach (var item in arr)
{
Console.Write(item + " ");
}
}
//堆排序
public static void HeapSort(int[] arr)
{
int length = arr.Length;
for (int i = 0; i < length; i++)
{
BuildMaxHead(arr, (length - i) / 2 - 1, length - i);
int maxValue = arr[0];
arr[0] = arr[length - i - 1];
arr[length - i - 1] = maxValue;
}
}
//构造大顶堆
public static void BuildMaxHead(int[] arr, int endIndex, int treeEndingIndex)
{
for (int i = endIndex; i >= 0; i--)
{
int maxIndex = i;
if (arr[2 * i + 1] > arr[maxIndex])
{
maxIndex = 2 * i + 1;
}
if ((2 * i + 2) < treeEndingIndex && arr[2 * i + 2] > arr[maxIndex])
{
maxIndex = 2 * i + 2;
}
if (maxIndex != i)
{
int temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
}
}
}