大家可以参考http://blog.csdn.net/morewindows/article/details/6709644,写的很详细
class HeapSort
{
public int[] arr { get; set; }
//TODO创建堆
//调整堆
public void AdjustHeap(int top,int boom)
{
int i = 2 * top + 1;
while (i < boom)
{
if (arr[i] < arr[i + 1])
{
//左节点小
if (arr[top] < arr[i])
{
return;
}
int temp = arr[top];
arr[top] = arr[i];
arr[i] = temp;
i = 2 * i + 1;
}
else
{
//右节点小
if (arr[top] < arr[i+1])
{
return;
}
int temp = arr[top];
arr[top] = arr[i+1];
arr[i+1] = temp;
i = 2 * i + 1;
}
}
}
public void BuildHeap()
{
for (int i = arr.Length / 2 - 1; i >= 0; i++)
{
AdjustHeap(i, arr.Length - 1);
}
}
public void SortHeap()
{
BuildHeap();
for (int i = 0; i < arr.Length - 1; i++)
{
int temp = arr[i];
arr[i] = arr[arr.Length - i];
arr[arr.Length - i] = temp;
AdjustHeap(i,arr.Length-i);
}
}
}