数组堆化

今天学习了数组堆化, 堆化启发我们的思维, 百尺竿头更进一步!

理解堆化

说是堆化, 其实就是利用树的性质表示在数组中, 利用下标和书上左右孩子对应关系.

公式

  • 左孩子下标 = 根下标 * 2 + 1
  • 右孩子下标 = 根下标 * 2 + 2

递归

递归 fixHead 函数来解决满足大顶堆或者小顶堆的问题, 说到递归, 我们一般会说递归结束条件, 数组越界或者已经符合条件, 结束递归.

源码

public class Main {
    public static void main(String[] args) {
        int[] arr = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ,0};
        for (int i = arr.length / 2 - 1; i > -1; i--) {
            fixHead(arr, i, arr.length - 1);
        }
    }

    public static void fixHead(int[] arr, int headIndex, int limitIndex) {
        int leftChildIndex = headIndex * 2 + 1;
        int rightChildIndex = headIndex * 2 + 2;
        if (leftChildIndex > limitIndex || rightChildIndex > limitIndex) {
            return;
        }
        int selectIndex = -1;
        if (arr[leftChildIndex] <= arr[rightChildIndex]
                && arr[leftChildIndex] < arr[headIndex]) {
            selectIndex = leftChildIndex;
        }
        if (arr[rightChildIndex] <= arr[leftChildIndex]
                && arr[rightChildIndex] < arr[headIndex]) {
            selectIndex = rightChildIndex;
        }
        if (selectIndex != -1) {
            int tempValue = arr[selectIndex];
            arr[selectIndex] = arr[headIndex];
            arr[headIndex] = tempValue;
            fixHead(arr, selectIndex, limitIndex);
        }
    }
}

结果

输入:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
输出:
[0, 1, 4, 2, 6, 5, 8, 3, 7, 9, 10]

转载于:https://www.cnblogs.com/haqueo/p/11483137.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值