堆排序就是对一个完全二叉树进行排序,首先将数组构造成一个大顶堆(小顶堆也可以),大顶堆就是整个完全二叉树的第一个元素最大,然后将首位进行换位,最后在将下次要构造的大顶堆的长度-1,直到最后只剩一个元素的时候就排序OK了 ,代码如下:
class Program
{
static void Main(string[] args)
{
int[] arr = { 2, 3, 4, 1, 100, 44, 22 };
HeapSort(arr);
foreach (int a in arr) {
Console.WriteLine(a);
}
}
public static void HeapSort(int[] arr) {
if (arr.Length <= 1) return;
//先将完全二叉树调整成大顶堆
HeapAdjustment(arr, arr.Length);
//每一次调整之后都将树的第一个元素和最后一个元素交换并在下次排序中舍去最后一个元素
for (int i = arr.Length - 1; i > 0; i--) {
swapFirstAndLast(arr, i);
HeapAdjustment(arr, i);
}
}
//将完全二叉树构造成大顶堆
public static void HeapAdjustment(int[] arr, int length)
{
for (int i = length / 2 - 1; i >= 0; i--) { //遍历完全二叉树的所有非叶子节点
for (int j = i * 2 + 1; j <= i * 2 + 2; j++)
{
int temp = 0; //临时交换变量
if (j < length)
{
if (arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
}
//交换完全二叉树的第一个元素和最后一个元素
public static void swapFirstAndLast(int[] arr, int last)
{
int temp = arr[0];
arr[0] = arr[last];
arr[last] = temp;
}
}