Domanda

I have the following Java Code that implements a max heap. It runs correctly,

List of numbers: 4, 1, 3, 2, 16, 9, 10, 14, 8, 7

MaxHeap result:

16 14 10 8 7 9 3 2 4 1

What I would like, is a change this code so as by giving an Index to make a Max-Heap only a part of the array.

For example if i give index=4

it should not affect the 4 first elements : 4 1 3 2 but to make a max heap with the remaining elements 16, 9 ,10, 14, 8, 7

So the final result shouuld be

4 1 3 2 16 14 10 9 8 7

Not other array should be used but only the given one:

public class Heapify {

    public static int[] Arr = {
        4, 1, 3, 2, 16, 9, 10, 14, 8, 7
    };
    public static int counter = 0;

    public static void main(String[] args) {

        heapMe();
        for (int krk = 0; krk < Arr.length; krk++) {
            System.out.println(Arr[krk]);
        }
    }

    public static void heapMe() {
        int kk;
        for (kk = (Arr.length) / 2 - 1; kk >= 0; kk--) {
            heapify(Arr, kk);
        }
    }

    public static void heapify(int[] Arr, int i) {
        int largest;
        int left = 2 * i + 1;
        int right = 2 * i + 2;
        if (((left < Arr.length) && (Arr[left] > Arr[i]))) {
            largest = left;
        } else {
            largest = i;
        }

        if (((right < Arr.length) && (Arr[right] > Arr[largest]))) {
            largest = right;
        }
        if (largest != i) {
            swap(i, largest);
            heapify(Arr, largest);
        }
    }

    private static void swap(int i, int largest) {
        int t = Arr[i];
        Arr[i] = Arr[largest];
        Arr[largest] = t;
    }
}
È stato utile?

Soluzione

You need to add an extra parameter n to the functions that refer to Arr.length, and replace all references to Arr.length with n. When you pass 4 to heapMe, it would heapify on the first four elements:

public static void heapMe(int n) {
    int kk;
    for (kk = n / 2 - 1; kk >= 0; kk--) {
        heapify(Arr, n, kk);
    }
}

public static void heapify(int[] Arr, int n, int i) {
    ... // Replace Arr.length with n throughout the body of the function
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top