堆排序之-小顶堆

这篇博客主要介绍如何用Java实现小顶堆,并在堆排序中应用小顶堆。作者建议对堆概念不熟悉的读者先阅读关于大顶堆的文章以加深理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不清楚堆概念的可以看这篇文章:堆排序之-大顶堆


用Java实现的小顶堆代码:

public class littleHeap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr = {3, 1, 6, 2, 9, 4, 5};
		heapSort(arr);
		for (int i : arr) {
			System.out.println(i);
		}
 	}
	
	public static void heapSort(int[] array) {
		//初始建堆
		for(int i=array.length/2-1; i>=0; i--) {
			adjustHeap(array, i, array.length);    //构建小顶堆
		}
		//堆排序
		for(int i=array.length-1; i>0; i--) {
			int temp = array[0];
			array[0] = array[i];
			array[i] = temp;
			adjustHeap(array, 0, i);
		}
	}
	
	public static void adjustHeap(int[] array, int i, int length) {
		int temp; //存放待调整的父节点
		int child;
		for(temp = array[i]; i*2 <= length-1; i = child) {
			child = i*2;
			if(child != (length-1) &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值