堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。
///
/// 堆排序
///
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);
Console.ReadKey();
}
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;
}
}
堆排序算法的时间复杂度不难证明为: O(n*logn) 。