java写的堆排序 代码

参照改写自 http://blog.kingsamchen.com/archives/547#viewSource


public class HeapSorter {

int temp = 0;

/*
* 输 入: Ary(int[]) - [in,out]排序数组 nIndex(int) - 起始下标 nHeapSize(int) - 堆大小 输
* 出: - 功 能: 从nIndex开始检查并保持最大堆性质
*/
void MaxHeapify(int Ary[], int nIndex, int nHeapSize) {
while (true) {
int nL = left(nIndex);
int nR = right(nIndex);
int nLargest;

if (nL <= nHeapSize && Ary[nIndex] < Ary[nL]) {
nLargest = nL;
} else {
nLargest = nIndex;
}

if (nR <= nHeapSize && Ary[nLargest] < Ary[nR]) {
nLargest = nR;
}

if (nLargest != nIndex) {
// 调整后可能仍然违反堆性质
swap(Ary, nLargest, nIndex);
nIndex = nLargest;
} else {
break;
}
}
}

/*
* 输 入: Ary(int[]) - [in,out]排序数组 nHeapSize(int) - [in]堆大小(zero-based) 输 出:
* - 功 能: 将一个数组改造为最大堆
*/
void BuildMaxHeap(int Ary[], int nHeapSize) {
for (int i = parent(nHeapSize); i >= 0; --i) {
MaxHeapify(Ary, i, nHeapSize);
}
}

/*
* 输 入: Ary(int[]) - [in,out]排序数组 nCount(int) - [in]元素个数 输 出: - 功 能:
* 对一个数组进行堆排序
*/
void HeapSort(int Ary[], int nCount) {
int nHeapSize = nCount - 1;

BuildMaxHeap(Ary, nHeapSize);

for (int i = nHeapSize; i >= 1; --i) {
swap(Ary, 0, i);
--nHeapSize;
MaxHeapify(Ary, 0, nHeapSize);
}
}

private void swap(int[] array, int index1, int index2) {
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}

private int left(int x) {
return (x << 1) + 1;
}

private int right(int x) {
return (x + 1) << 1;
}

private int parent(int x) {
return ((x + 1) >> 1) - 1;
}

public static void main(String[] s) {
int a[] = {6, 16, 4, 10, 14, 7, 9, 3, 2, 8, 1 };
new HeapSorter().HeapSort(a, 10);
for (int i : a) {
System.out.print(i + ",");
}
}
}

输出结果是:1,2,3,4,6,7,8,9,10,14,16,
未做优化.原文就不贴出了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值