用数组表示大根堆

用数组表示大根堆

在这里插入图片描述

package bin2;

import java.util.Arrays;

//用数组表示大根堆
public class TestSortDemo {
    //向下调整
    //时间复杂度:log2^n
    public static void adjustDown(int[] array,int root,int len){
        int parent=root;
        int child=2*parent+1;

        while (child<len) {
            //左孩子是否大于右孩子
            if (child + 1 < len && array[child] < array[child + 1]) {
                child++;//保存最大值的下标
            }

            //如果孩子结点大于父亲结点,交换,如果有孩子结点,然后接着向下调整
            if (array[child] > array[parent]) {
                int temp = array[child];
                array[child] = array[parent];
                array[parent] = temp;
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    //此时已经是一个大根堆
    //时间复杂度:(n/2) * log2^n
    public static void createHeap(int[] array){
        for (int i = (array.length-1-1)/2; i >=0 ; i--) {
            adjustDown(array,i,array.length);
        }
    }


    //将大根堆从小到大排序
    public static void heapSort(int[] array){
        createHeap(array);//首先要是一个大根堆
        int end=array.length-1;
        //将末尾结点与0号位结点交换,调整,一直到end调整到0结点
        while (end>0){
            int temp=array[end];
            array[end]=array[0];
            array[0]=temp;
            adjustDown(array,0,end);
            end--;
        }
    }


    public static void main(String[] args) {
        int[] array={27,15,19,18,28,34,65,49,25,37};
        System.out.println(Arrays.toString(array));
        heapSort(array);
        System.out.println(Arrays.toString(array));
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值