From 1a9937c7cb981a46a9251a0e21669c73ac1aa3c0 Mon Sep 17 00:00:00 2001 From: Jainam Kothari <87520388+Jainam1401@users.noreply.github.com> Date: Wed, 13 Jul 2022 23:10:21 +0530 Subject: [PATCH] Add index validation to Min Heap and Max Heap (#3189) Co-authored-by: Andrii Siriak --- .../datastructures/heaps/{GenericHeap => GenericHeap.java} | 0 .../java/com/thealgorithms/datastructures/heaps/MaxHeap.java | 4 ++++ .../java/com/thealgorithms/datastructures/heaps/MinHeap.java | 4 ++++ 3 files changed, 8 insertions(+) rename src/main/java/com/thealgorithms/datastructures/heaps/{GenericHeap => GenericHeap.java} (100%) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap b/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java similarity index 100% rename from src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap rename to src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 13eb7a20c..e19d4c718 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -43,6 +43,10 @@ public class MaxHeap implements Heap { // Get the key of the element at a given index private double getElementKey(int elementIndex) { + if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) { + throw new IndexOutOfBoundsException("Index out of heap range"); + } + return maxHeap.get(elementIndex - 1).getKey(); } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java index b25796154..6d5d6870c 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java @@ -37,6 +37,10 @@ public class MinHeap implements Heap { // Get the key of the element at a given index private double getElementKey(int elementIndex) { + if ((elementIndex <= 0) || (elementIndex > minHeap.size())) { + throw new IndexOutOfBoundsException("Index out of heap range"); + } + return minHeap.get(elementIndex - 1).getKey(); }