堆排序

package al;

import java.util.Arrays;

/**
 * 堆排序.
 * 
 * @author chenlb 2008-12-28 下午03:52:53
 */
public class HeapSort {

	private static int parentIdx(int childIdx) {
		return (childIdx - 1) / 2; // 索引从0开始, 注意childIdx=0时返回0
	}

	private static int leftChildIdx(int parentIdx) {
		return parentIdx * 2 + 1;
	}

	/**
	 * 构建大顶堆.
	 * 
	 * @author chenlb 2008-12-28 下午03:52:23
	 */
	private static void buildMaxHeap(int[] datas) {
		int lastIdx = datas.length - 1;
		for (int i = parentIdx(lastIdx); i >= 0; i--) {
			int k = i;
			/* boolean isHeap = false; */
			/* 先比较左边的兄弟,如果不满足再比较父节点 */
			while (/* !isHeap && */leftChildIdx(k) <= lastIdx) {
				int j = leftChildIdx(k);
				if (j < lastIdx) { // 有两个孩子
					if (datas[j] <= datas[j + 1]) { // j+1 比较大, 选择大的
						j++;
					}
				}

				if (datas[k] > datas[j]) { // 父的比较大
					/* isHeap = true; */
					break;
				} else {
					SortUtil.swap(datas, k, j);
					k = j;
				}
			}
		}
	}

	/**
	 * 堆顶改变, 要维护大顶堆.
	 * 
	 * @author chenlb 2008-12-28 下午03:53:04
	 */
	private static void maintainMaxHeap(int[] datas, int lastIdx) {
		int k = 0;
		while (k <= parentIdx(lastIdx)) {
			int j = leftChildIdx(k);
			if (j < lastIdx) { // 有两个孩子
				if (datas[j] <= datas[j + 1]) { // j+1 比较大, 选择大的
					j++;
				}
			}
			if (datas[k] < datas[j]) { // 父结点比较小
				SortUtil.swap(datas, k, j);
				k = j;
			} else {
				break;
			}
		}
	}

	public static int[] sort(int[] datas) {
		buildMaxHeap(datas);
		int lastIdx = datas.length - 1;
		while (lastIdx > 0) {
			SortUtil.swap(datas, 0, lastIdx);
			lastIdx--;
			if (lastIdx > 0) {
				maintainMaxHeap(datas, lastIdx);
			}
		}
		return datas;
	}

	public static void main(String[] args) {
		int[] datas = { 5, 1, 3, 4, 9, 2, 7, 6, 5 };// {2, 9, 3, 7, 8, 6, 4, 5,
													// 0, 1};

		/*
		 * buildMaxHeap(datas); System.out.println(Arrays.toString(datas));
		 */

		sort(datas);
		System.out.println(Arrays.toString(datas));

		// datas = SortUtil.randomDates(10);
		// sort(datas);
		// System.out.println(Arrays.toString(datas));

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值