main 函数中调用:
var data = new int[] {5,7,6,4,1,9,3};
heapSort(data);
heap sort 实现:
static void heapSort(int[] DArray)
{
var ArrayLength = DArray.Length;
for (int i= ArrayLength / 2;i>=0;i--)
{
heapAdjust(DArray,i, ArrayLength);
}
var temp = DArray[0];
DArray[0] = DArray[ArrayLength - 1];
DArray[ArrayLength - 1] = temp;
var sublength = ArrayLength - 1;
while (sublength>1)
{
heapAdjust(DArray, 0, sublength);
temp = DArray[0];
DArray[0] = DArray[sublength - 1];
DArray[sublength - 1] = temp;
sublength = sublength - 1;
}
}
static void heapAdjust(int[] da, int parent, int length)
{
var temp = da[parent];
var child = parent * 2 + 1;
while (child<length)
{
if (child+1<length && da[child]<da[child+1])
{
child++;
}
if (da[child] > temp)
{
da[parent]= da[child];
parent = child;
child = child * 2 + 1;
}
else {
break;
}
}
da[parent] = temp;
}