简体   繁体   中英

How can I fix my remove(Comparable e) method on a Max Heap?

I'm trying to remove(Comparable e) object say remove(2), but when I try to remove it removes the incorrect node in the heap and not the one that I want it to be removed.

This is what the output looks like.

The heap before removing Redwoods NP:

Bryce Canyon NP Redwoods NP Joshua Tree NP Zion NP Yosemite NP Lassen Volcanic NP 

[
null, 
Bryce Canyon NP, 
Redwoods NP, 
Joshua Tree NP, 
Zion NP, 
Yosemite NP, 
Lassen Volcanic NP
]

After removing Redwoods NP:

Bryce Canyon NP Redwoods NP Joshua Tree NP Zion NP Redwoods NP 

[
null, 
Bryce Canyon NP, 
Redwoods NP, 
Joshua Tree NP, 
Zion NP, 
Redwoods NP, 
Lassen Volcanic NP
]

BUILD SUCCESSFUL (total time: 1 second)

Expected

[
Bryce Canyon NP,
Joshua Tree NP, 
Zion NP, 
Yosemite NP, 
Lassen Volcanic NP
] 

My code

public void remove(Comparable e) throws NoSuchElementException {

    if (size == 0) {
        throw new NoSuchElementException("Heap is empty! Nothing to be removed");
    }

    Comparable toRemove = e;
    System.out.println(Arrays.toString(heapData));
    Comparable temp = heapData[size-1];
    heapData[size-1] = toRemove;
    toRemove = temp;
    size--;
    maxHeapify(heapData,size);  
}

My Add(Comparable e) code method

public void add(Comparable e) {
        if (size == heapData.length - 1) {
            doubleSize();
        }
        int position = ++size;
        for (; position > 1 && e.compareTo(heapData[position / 2]) < 0; position = position / 2) {
            heapData[position] = heapData[position / 2];
            maxHeapify(heapData, position);
        }

        heapData[position] = e;

    }

here:

toRemove = temp;

// this line is wrong, you are only changing the object in heap, not in array. instead first write a method that finds position of e in the array and assign the temp object to that position

add a method:

int findRemoveableIndex(Comparable[] input, Comparable e) {
    for(int i = 0; i < input.length; i++) {
        if(input[i].equals(e)) { // or == 
            return i;
        }
    }
    return -1;
}

then, instead of above assignment do this:

heapData[findRemoveableIndex(heapData, e)] = temp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM