JAVA 实现算法 - 堆排序

这里的堆是堆数据结构,而不是java中的垃圾收集存储。

堆(二叉堆)是一个数组,可以被看成一个近似的完全二叉树。

二叉堆可以分为2种形式:最大堆、最小堆

  • 最大堆
A[parent(i)] >= A[i]
  • 最小堆
A[parent(i)] <= A[i]
public int heapSize = 7;
public Integer[] a = new Integer[]{10, 7, 19, 3, 6, 46, 44, 45};
// 下标                              1,2, 3, 4,5, 6, 7, 8
public void heapSort() {
    buildMaxHeap(a);
    System.out.println(Arrays.asList(a));
    for (int i = a.length; i >= 2; i--) {
        // exchange A[1] with A[i]
        Integer key = a[i - 1];
        a[i - 1] = a[0];
        a[0] = key;
        this.heapSize = this.heapSize - 1;
        maxHeapIfy(1);
    }
}
public void buildMaxHeap(Integer[] A) {
    heapSize = a.length;
    for (int i = A.length / 2; i > 0; i--) {
        maxHeapIfy(i);
    }
}
public void maxHeapIfy(int i) {
    // 查找左右子节点
    Integer leftIndex = left(i);
    Integer rightIndex = right(i);
    // 最大节点
    Integer largest;
    if (leftIndex <= a.length - 1 && a[leftIndex - 1] > a[i - 1]) {
        largest = leftIndex;
    } else {
        largest = i;
    }
    if (rightIndex <= a.length - 1 && a[rightIndex - 1] > a[largest - 1]) {
        largest = rightIndex;
    }
    if (largest != i) {
        // exchange A[i] with A[largest]
        Integer key = a[i - 1];
        a[i - 1] = a[largest - 1];
        a[largest - 1] = key;
        maxHeapIfy(largest);
    }
}
public int left(int i) {
    return 2 * i;
}
public int right(int i) {
    return 2 * i + 1;
}
public int parent(int i) {
    return i / 2;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值