数据结构与算法(Java) 13:减堆[堆操作]

减堆,即(例如)从大根堆中去掉根节点,并调整剩余部分为大根堆。

思路 将大根堆根节点与最后一个叶节点交换位置,然后将大根堆有效大小减1,即去掉最后一个叶节点,再进行一次heapify。

package section1;

import java.util.Arrays;

public class HeapReduction {
    public static int heapReduction(int[] arr, int heapSize){
        swap(arr, 0, heapSize-1);
        return heapSize - 1;
    }

    public static void swap(int[] arr, int a, int b){
        int f = arr[a];
        arr[a] = arr[b];
        arr[b] = f;
    }

    public static void heapify(int[] arr, int index, int heapSize){
        int L = 2 * index + 1;
        while (L < heapSize){
            int large = L + 1 < heapSize && arr[L + 1] > arr[L] ? L + 1 : L;
            if (arr[large] > arr[index]) {
                swap(arr, index, large);
                index = large;
                L = 2 * index + 1;
            }
            else break;
        }
    }

    public static void main(String[] args){
        int[] arr = {6, 5, 4, 3, 1};
        int heapSize = heapReduction(arr, arr.length);
        heapify(arr, 0, heapSize);
        for (int i = 0; i < heapSize; i++)
            System.out.print(arr[i] + " ");
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105344759