Skip to content

MinHeap and MaxHeap realisations are broken #3158

@Boiarshinov

Description

@Boiarshinov

MinHeap and MaxHeap implementation are broken.
Instance of these heaps couldn't be instanciated with any not empty list of elements.

Here is a test code to reproduce:

@Test
void createFromList() {
    var elements = List.of(
            new HeapElement(5)
    );
    MaxHeap heap = new MaxHeap(elements);
    //similar with MinHeap
}

Stacktrace:

java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 1

	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
	at java.base/java.util.Objects.checkIndex(Objects.java:359)
	at java.base/java.util.ArrayList.get(ArrayList.java:427)
	at com.thealgorithms.datastructures.heaps.MaxHeap.getElementKey(MaxHeap.java:46)
	at com.thealgorithms.datastructures.heaps.MaxHeap.toggleUp(MaxHeap.java:59)
	at com.thealgorithms.datastructures.heaps.MaxHeap.insertElement(MaxHeap.java:97)
	at com.thealgorithms.datastructures.heaps.MaxHeap.<init>(MaxHeap.java:20)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions