using System;
public class HelloWorld
{
public static void Main()
{
int[] arr = { 23, 44, 66, 76, 98, 11, 3, 9, 7 };
Console.WriteLine("排序前的数组:");
foreach (int item in arr)
{
Console.Write(item + ",");
}
Console.WriteLine();
HeapSort(arr, arr.Length - 1);
Console.WriteLine("排序后的数组:");
foreach (int item in arr)
{
Console.Write(item + ",");
}
}
static void MaxHeapify(int[] array, int n, int i)
{
int largest = i;
int lson = i * 2 + 1;
int rson = i * 2 + 2;
if (lson <= n && array[largest] < array[lson])
{
largest = lson;
}
if (rson <= n && array[largest] < array[rson])
{
largest = rson;
}
if (largest != i)
{
Swap(ref array[largest], ref array[i]);
MaxHeapify(array, n, largest);
}
}
static void HeapSort(int[] array, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
{
MaxHeapify(array, n, i);
}
for (int i = n; i > 0; i--)
{
Swap(ref array[i], ref array[0]);
MaxHeapify(array, i - 1, 0);
}
}
static void Swap(ref int a, ref int b)
{
int temp = b;
b = a;
a = temp;
}
}