关于二叉堆的“上浮”与“下沉”

import java.util.Arrays;

public class ErChaDui {
	/**
	 * 上浮调整
	 * 
	 * @param array 待调整的堆
	 */
	private static void upAdjust(int[] array) {
		int childIndex = array.length - 1;
		int parentIndex = (childIndex - 1) / 2;
		// temp保存插入的叶子节点值,用于最后的赋值
		int temp = array[childIndex];
		while (childIndex > 0 && temp < array[parentIndex]) {
			// 无需真正交换,单向赋值即可
			array[childIndex] = array[parentIndex];
			childIndex = parentIndex;
			parentIndex = (parentIndex - 1) / 2;
		}
		// 最后将值给它
		array[childIndex] = temp;

	}

	/**
	 * 下沉调整
	 * 
	 * @param array       待调整的堆
	 * @param parentIndex 要下沉的父节点
	 * @param lenght      堆得有效大小
	 */
	private static void downAdjust(int[] array, int parentIndex, int length) {
		// temp保存父节点值,用于最后赋值
		int temp = array[parentIndex];
		// 左孩子
		int childIndex = 2 * parentIndex + 1;
		while (childIndex < length) {
			// 如果有右孩子,且右孩子小于左孩子的值,则定位到右孩子
			if (childIndex + 1 < length && array[childIndex] + 1 < array[childIndex]) {
				childIndex++;
			}
			// 如果父节点小于任何一个孩子的值,则直接跳出
			if (temp <= array[childIndex]) {
				break;
			}
			// 无需真正交换,单向赋值即可
			array[parentIndex] = array[childIndex];
			parentIndex = childIndex;
			childIndex = 2 * childIndex + 1;
		}
		array[parentIndex] = temp;
	}

	/**
	 * 构建堆
	 * 
	 * @param array 待调整的堆
	 */
	private static void buildHeap(int[] array) {
		// 从最后一个非叶子节点开始,以此做下沉调整
		for (int i = (array.length - 2) / 2; i >= 0; i--) {
			downAdjust(array, i, array.length);
		}
	}
	
	//进行测试
	public static void main(String[] args) {
		int[] array = new int[] { 1, 3, 2, 6, 7, 8, 9, 10 };
		upAdjust(array);
		System.out.println(Arrays.toString(array));

		array = new int[] { 7, 1, 3, 10, 5, 2, 8, 9, 6 };
		buildHeap(array);
		System.out.println(Arrays.toString(array));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl精

面试很多问题,积攒不容易

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值