六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 42|回复: 0

java写的堆排序 代码

[复制链接]

升级  96%

10

主题

10

主题

10

主题

童生

Rank: 1

积分
48
 楼主| 发表于 2013-2-3 10:28:39 | 显示全部楼层 |阅读模式
参照改写自  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,
未做优化.原文就不贴出了
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表