堆和栈的概念和区别 python_1.7 堆排序

上方又没些 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值