构造大顶堆

package com.xiejianjun.day09;

import java.util.Arrays;

/**
 * @author bilibilidick
 * @version 2022 04
 * @date 2022/4/24 12:15
 */

public class Heapsort {

    public static void main(String[] args) {
        int[] tree = {1, 2, 3, 4, 5, 6, 7};
        build_heap(tree);
        System.out.println("层序遍历此数组转化为大顶堆后的结果:" + Arrays.toString(tree));

    }

    // 交换两个结点,因为能执行找个方法就代表已经判断过数组越界的问题了,故不在此判断越界
    public static void swap(int[] tree,int parent,int child) {
        int temp = 0;
        temp = tree[parent];
        tree[parent] = tree[child];
        tree[child] = temp;
    }

    // 从下到上构建大顶堆
    public static void build_heap(int[] tree) {
        int last_node = tree.length - 1;
        int last_parent = (last_node - 1) / 2;
        for (int i = last_parent; i >= 0 ; i--) {
            heapify(tree, i, tree.length);
        }
    }

    // 构造顶堆的方法,只对被打乱的结点的子树做递归,所以heapify(max)
    public static void heapify(int[] tree, int i, int n) {
        if (i < n) {
            int max = i;
            int left = 2 * i + 1;
            int right = 2 * i + 2;
            if (left < n && tree[left] > tree[max]) {
                    max = left;
            }
            if (right < n && tree[right] > tree[max]) {
                    max = right;
            }
            if (i != max) {
                swap(tree, i, max);
                heapify(tree,max,n);
            }

        }
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值