Java排序算法--堆排序

public class HeapSort3 {
	public static void main(String[] args) {
		int[] arr = {312,126,272,226,28,165,123,8,12};
//		int[] arr = SortTestHelper.getRandomArray(20, 0, 2);
		System.out.println("堆排序前:"+Arrays.toString(arr));
		//堆排序
		heapSort(arr, arr.length);
		System.out.println("堆排序后:"+Arrays.toString(arr));
	}
	
	private static void heapSort(int[] arr, int count) {
		//完成构建大顶堆
		//(count-2)/2获取最后一个非叶子节点
		for(int i=(count-2)/2; i>=0; i--)
			shiftDown(arr, count, i);
		System.out.println("构建完成的大顶堆:"+Arrays.toString(arr));
		
		//将大顶堆头结点(最大数)与最后一个元素交换位置,然后除去最后这个最大的元素,再shiftDown操作维护该(除去最后一个元素的数组)堆为大顶堆。循环直到升序排序完成
		for(int j=count-1; j>0; j--) {
			swap(arr, 0, j);
			shiftDown(arr, j, 0);
		}
	}
	
	/**
	 * 
	 * @param arr 数组
	 * @param count	元素个数
	 * @param currentRoot 当前根节点的下标
	 */
	private static void shiftDown(int[] arr, int count ,int currentRoot) {
		while(2*currentRoot+1 < count) {
			int max = 2*currentRoot+1; //初始赋值left孩子
			if(max+1 < count && arr[max+1] > arr[max])
				max += 1;
			if(arr[currentRoot] >= arr[max])
				break;
			swap(arr, currentRoot, max);
			currentRoot = max;
		}
	}
	
	//交换
	public static void swap(int[] arr, int n, int m) {
		int temp = arr[n];
		arr[n] = arr[m];
		arr[m] = temp;
	}
}
--------------------- 
作者:stoneWang_L 
来源:CSDN 
原文:https://blog.csdn.net/stoneWang_L/article/details/89190250 
版权声明:本文为博主原创文章,转载请附上博文链接!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值