堆排序模板

排序 专栏收录该内容
1 篇文章 0 订阅
public class Main {

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9, 11};
        headSort(arr, arr.length);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

    public static void headSort(int[] tree, int n) {
        buildHeap(tree, n);
        for (int i = n - 1; i >= 0; i--) {
            swap(tree, i, 0);
            heapfiy(tree, 0, i);
        }
    }

    public static void buildHeap(int[] tree, int n) {
        int parentIndex = (n - 1) >> 1;
        for (int i = parentIndex; i >= 0; i--) {
            heapfiy(tree, i, n);
        }
    }

    public static void heapfiy(int[] tree, int index, int n) {
        if (index >= n) {
            return;
        }
        int leftChildIndex = (index << 1) + 1;
        int rightChildIndex = (index << 1) + 2;
        int maxIndex = index;
        if (leftChildIndex < n && tree[maxIndex] < tree[leftChildIndex]) {
            maxIndex = leftChildIndex;
        }
        if (rightChildIndex < n && tree[maxIndex] < tree[rightChildIndex]) {
            maxIndex = rightChildIndex;
        }
        if (maxIndex != index) {
            swap(tree, index, maxIndex);
            heapfiy(tree, maxIndex, n);
        }
    }

    public static void swap(int[] tree, int aIndex, int bIndex) {
        int temp = tree[aIndex];
        tree[aIndex] = tree[bIndex];
        tree[bIndex] = temp;
    }

}

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值