# C#算法设计排序篇之06-堆排序（附带动画演示程序）

C#算法设计概述

## 示例

```public class Program {

public static void Main(string[] args) {
int[] array = { 43, 69, 11, 72, 28, 21, 56, 80, 48, 94, 32, 8 };

HeapSort(array);
ShowSord(array);

}

private static void ShowSord(int[] array) {
foreach (var num in array) {
Console.Write(\$"{num} ");
}
Console.WriteLine();
}

private static void HeapSort(int[] array) {
MaxHeap(array);
for (int i = array.Length - 1; i > 0; i--) {
Swap(ref array[0], ref array[i]);
Heapify(array, 0, i);
}
}

private static void MaxHeap(int[] array) {
for (int i = array.Length / 2 - 1; i >= 0; i--) {
Heapify(array, i, array.Length);
}
}

private static void Heapify(int[] array, int index, int size) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int large = index;

if (left < size && array[left] > array[large]) {
large = left;
}
if (right < size && array[right] > array[large]) {
large = right;
}
if (index != large) {
Swap(ref array[index], ref array[large]);
Heapify(array, large, size);
}
}

private static void Swap(ref int first, ref int second) {
int t = first;
first = second;
second = t;
}

}```

以上是堆排序算法的一种实现，以下是这个案例的输出结果：

`8 11 21 28 32 43 48 56 69 72 80 94`

## AlgorithmMan

AlgorithmMan by Iori，AlgorithmMan是使用C#开发的一套用于算法演示的工具。

(6)