堆排序

import java.util.HashMap;

public class heapSort {

    public static void sort(int[] a) {
        // 循环建立初始堆,若父节点索引为i,那么左节点的索引为i*2+1,即左节点为a.length时,其父节点应当小于a.length/2
        for (int i = a.length / 2; i >= 0; i--) {// 遍历存在子节点的父节点
            adjustHeap(a, i, a.length - 1);
        }

        // 进行n-1次循环完成排序
        for (int i = a.length - 1; i > 0; i--) {
            // 最后一个元素和第一个元素进行交换
            int temp = a[i];
            a[i] = a[0];
            a[0] = temp;

            adjustHeap(a, 0, i);
        }
    }

    // 将数组转换为大根堆,大根堆的根节点为数组中的最大值
    public static void adjustHeap(int[] a, int parent, int length) {
        int temp = a[parent]; // 父节点的值
        int child = 2 * parent + 1; // 左子节点的索引

        while (child < length) {// 判断左节点是否为最大索引
            // 如果有右孩子结点,并且右孩子结点的值大于左孩子结点,则选取右孩子结点
            if (child + 1 < length && a[child] < a[child + 1]) {
                child ++;// 将左子节点转换为右子节点
            }
            // 当父节点的值直接大于子节点的值时,直接退出
            if (temp > a[child])
                break;
            // 将子节点的值赋值给父节点
            a[parent] = a[child];
            // 选取子节点的左子节点继续向下筛选
            parent = child;
            child = 2 * parent + 1;
        }
        // 若发生交换,此时parent代表子节点索引,没有发生交换,此时parent仍旧代表父节点索引
        a[parent] = temp;
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值