堆排序基本思路&简洁代码模板(Java实现)

堆排序 是利用 这种数据结构而设计的一种排序算法,堆排序是一种选择排序,它的最坏,最好,平均时间复杂度均为O(nlogn),它是不稳定排序。

堆的性质:是一棵完全二叉树,并且父节点的值大于它所有子节点的值(最大堆)

堆调整(heapfiy):若子节点c1,c2有大于父节点parent的值,则与父节点交换。

堆排序的基本思想是:将待排序序列构造成一个最大堆,此时,整个序列的最大值就是堆顶的根节点。将其与末尾元素进行交换,此时末尾就为最大值。然后将剩余n-1个元素重新构造成一个堆,这样会得到n个元素的次小值。如此反复执行,便能得到一个有序序列了

public class HeapSort {

	//堆排序
	private static void heapSort(int[] tree, int n) {
		buildHeap(tree, n);
		for(int i = n-1;i >= 0;i--) {
			swap(tree,0,i);//把最大的放最后面
			heapify(tree, 0, i);//调整
		}
	}

	//构建最大堆
	private static void buildHeap(int[] tree, int n) {
		int lastNode = tree.length-1;
		int parent = (lastNode-1)/2;
		//从下往上构建
		for(int i = parent;i >= 0;i--) {
			heapify(tree,i,n);
		}
	}

	//在左子节点,右子节点中找出最大值与父节点替换,形成局部最大堆
	private static void heapify(int[] tree, int i, int n) {
		int max = i;
		int c1 = 2*i+1;
		int c2 = 2*i+2;
		if(c1<n&&tree[c1]>tree[max]) {
			max = c1;
		}
		if(c2<n&&tree[c2]>tree[max]) {
			max = c2;
		}
		if(max!=i) {
			swap(tree,i,max);
			heapify(tree,max,n);
		}
	}
	
	//交换
	private static void swap(int[] a, int i, int j) {
		int temp = a[i];
		a[i] = a[j];
		a[j] = temp;
	}
	
	public static void main(String[] args) {
		int tree[] = {2,5,3,1,10,4};
		heapSort(tree,tree.length);
		System.out.println(Arrays.toString(tree));//[1, 2, 3, 4, 5, 10]
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值