-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
namespace CSharpLearning
-
{
-
using System;
-
-
-
-
-
public static class Program
-
{
-
-
-
-
public static void Main()
-
{
-
int[] a = { 1, 14, 6, 2, 8, 66, 9, 3, 0, 10, 5, 34, 76, 809, 4, 7 };
-
Console.WriteLine("Before Heap Sort...");
-
foreach (int i in a)
-
{
-
Console.Write(i + " ");
-
}
-
-
Console.WriteLine("\r\n--------------------");
-
Console.WriteLine("In Heap Sort...");
-
HeapSort(a);
-
Console.WriteLine("--------------------");
-
Console.WriteLine("After Heap Sort...");
-
foreach (int i in a)
-
{
-
Console.Write(i + " ");
-
}
-
-
Console.WriteLine(string.Empty);
-
}
-
-
-
-
-
-
-
-
private static void HeapSort(int[] a)
-
{
-
BuildMaxHeap(a);
-
Console.WriteLine("Build max heap:");
-
foreach (int i in a)
-
{
-
Console.Write(i + " ");
-
}
-
-
Console.WriteLine("\r\nMax heap in each iteration:");
-
for (int i = a.Length - 1; i > 0; i--)
-
{
-
Swap(ref a[0], ref a[i]);
-
MaxHeaping(a, 0, i);
-
-
-
for (int j = 0; j < i; j++)
-
{
-
Console.Write(a[j] + " ");
-
}
-
-
Console.WriteLine(string.Empty);
-
}
-
}
-
-
-
-
-
-
-
-
private static void BuildMaxHeap(int[] a)
-
{
-
for (int i = (a.Length / 2) - 1; i >= 0; i--)
-
{
-
MaxHeaping(a, i, a.Length);
-
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
private static void MaxHeaping(int[] a, int i, int heapSize)
-
{
-
int left = (2 * i) + 1;
-
int right = 2 * (i + 1);
-
int large = i;
-
-
-
if (left < heapSize && a[left] > a[large])
-
{
-
large = left;
-
}
-
-
-
if (right < heapSize && a[right] > a[large])
-
{
-
large = right;
-
}
-
-
-
if (i != large)
-
{
-
Swap(ref a[i], ref a[large]);
-
MaxHeaping(a, large, heapSize);
-
}
-
}
-
-
-
-
-
-
-
private static void Swap(ref int a, ref int b)
-
{
-
int tmp = a;
-
a = b;
-
b = tmp;
-
}
-
}
-
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
算法 Heap sort
原文:http://www.cnblogs.com/gavanwanggw/p/6785920.html