大根堆 java

本文介绍了完全二叉树的概念,并重点讲解了大根堆的特性,即根结点大于其左右子结点。同时,文章还探讨了如何在Java中建立大根堆以及如何利用大根堆实现堆排序的过程。

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

完全二叉树
  • 完全二叉树是指从根结点到倒数第二层全部填充,最后一层可以不完全填充,其叶子结点都靠左对齐,如果结点的度为1 ,则该结点只有左孩子
  • 一棵完全二叉树,分为大根堆和小根堆
  • 大根堆:根结点最大,q其它结点满足 根结点>左结点>右结点
  • 小根堆:根节点最小,其他结点满足 根结点<左结点<右结点
    我们采用用数组存储节点,当前节点为i时计算:父结点(i+1)/2,子女结点:2i+1(左结点),2i+2(右结点),如第0个结点左右子结点下标分别为1和2
建立一个大根堆
//建立大根堆的过程---------------->时间复杂度:log1+log2+...+logN-1==O(N)
public static void heapSort(int[] a) {
        if (a == null || a.length < 2) {
            return;
        }
        for (int i = 0; i < a.length; i++) {
            heapInsert(a, i);  //每次都调整大根堆
        }
    }

    //调整的过程
    public static void heapInsert(int[] a, int index) {
        while (a[index] > a[(index - 1) / 2]) { //此结点大于它的父节点,进行交换
            swap(a, index, (index - 1) / 2);
            index = (index - 1) / 2; //继续上一个父节点进行比较
        }
    }

    public static void swap(int[] a, int j, int i) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
实现堆排序

每次把大根堆的对顶数据交换到最后位置,heapSize–,调整缩小范围后的堆

public class DuiSort {

    public static void heapSort(int[] a) {
        if (a == null || a.length < 2) {
            return;
        }

        for (int i = 0; i < a.length; i++) {
            heapInsert(a, i);  //每次都调整大根堆
        }
        int heapSize = a.length; //用来记录每次排序调整后,待排序调整的个数
        swap(a,0,--heapSize); //将堆顶元素交换到最后的位置
        while(heapSize > 0){
             heappify(a, 0, heapSize);
             swap(a, 0, --heapSize);
        }
    }

    public static void heapInsert(int[] a, int index) {
        while (a[index] > a[(index - 1) / 2]) {
            swap(a, index, (index - 1) / 2);
            index = (index - 1) / 2;
        }
    }

    public static void swap(int[] a, int j, int i) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    //修改某值后,进行调整大根堆;也可以在弹出堆顶的元素后,heapSize--,调用此函数调整堆
    public static void heappify(int[] a, int index, int heapSize){   //堆数据量
          int left = 2*index + 1;  //左孩子
           while(left < heapSize){
               //比较左右孩子
               int large = left + 1 < heapSize && a[left + 1] > a[left] ? left + 1: left;
               large = a[index] > a[large] ? index : large;
               if(large == index){
                   break;    //不用交换
               }
               swap(a, large, index);
               index = large;
               left = index * 2 + 1; //往下走
           }
    }

    public static void main(String[] args) {
        int[] array = new int[]{1, 3, 5, 2, 9, 6, 8, 10, 4, 7};
        heapSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值