上方又没些 C# 的堆排序,艾孜尔江补充如下:
///
/// 堆排序
///
/// 待排序数组
static void HeapSort(int[] arr)
{
int vCount = arr.Length;
int[] tempKey = new int[vCount + 1];
// 元素索引从1开始
for (int i = 0; i < vCount; i++)
{
tempKey[i + 1] = arr[i];
}
// 初始数据建堆(从含最后一个结点的子树开始构建,依次向前,形成整个二叉堆)
for (int i = vCount / 2; i >= 1; i--)
{
Restore(tempKey, i, vCount);
}
// 不断输出堆顶元素、重构堆,进行排序
for (int i = vCount; i > 1; i--)
{
int temp = tempKey[i];
tempKey[i] = tempKey[1];
tempKey[1] = temp;
Restore(tempKey, 1, i - 1);
}
//排序结果
for (int i = 0; i < vCount; i++)
{
arr[i] = tempKey[i + 1];
}
}
///
/// 二叉堆的重构(针对于已构建好的二叉堆首尾互换之后的重构)
///
///
/// 根结点j
/// 结点数
static void Restore(int[] arr, int rootNode, int nodeCount)
{
while (rootNode <= nodeCount / 2) // 保证根结点有子树
{
//找出左右儿子的最大值
int m = (2 * rootNode + 1 <= nodeCount && arr[2 * rootNode + 1] > arr[2 * rootNode]) ? 2 * rootNode + 1 : 2 * rootNode;
if (arr[m] > arr[rootNode])
{
int temp = arr[m];
arr[m] = arr[rootNode];
arr[rootNode] = temp;
rootNode = m;
}
else
{
break;
}
}
}
艾孜尔江
艾孜尔江
bju***ft@sina.com2个月前 (10-08)