Skip to content

Commit 1a9937c

Browse files
Jainam1401siriak
andauthored
Add index validation to Min Heap and Max Heap (TheAlgorithms#3189)
Co-authored-by: Andrii Siriak <siryaka@gmail.com>
1 parent b2f6827 commit 1a9937c

File tree

3 files changed

+8
-0
lines changed

3 files changed

+8
-0
lines changed

src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ public HeapElement getElement(int elementIndex) {
4343

4444
// Get the key of the element at a given index
4545
private double getElementKey(int elementIndex) {
46+
if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) {
47+
throw new IndexOutOfBoundsException("Index out of heap range");
48+
}
49+
4650
return maxHeap.get(elementIndex - 1).getKey();
4751
}
4852

src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ public HeapElement getElement(int elementIndex) {
3737

3838
// Get the key of the element at a given index
3939
private double getElementKey(int elementIndex) {
40+
if ((elementIndex <= 0) || (elementIndex > minHeap.size())) {
41+
throw new IndexOutOfBoundsException("Index out of heap range");
42+
}
43+
4044
return minHeap.get(elementIndex - 1).getKey();
4145
}
4246

0 commit comments

Comments
 (0)