Skip to content

Commit 575ce6d

Browse files
committed
Fix
1 parent 27e5dda commit 575ce6d

File tree

1 file changed

+6
-8
lines changed
  • src/main/java/com/thealgorithms/datastructures/heaps

1 file changed

+6
-8
lines changed

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

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ public class MaxHeap implements Heap {
3333

3434
/**
3535
* Constructs a new MaxHeap from a list of elements.
36-
* Null elements in the input list are ignored with a warning message.
36+
* Null elements in the input list are ignored.
3737
*
3838
* @param listElements List of HeapElement objects to initialize the heap
3939
* @throws IllegalArgumentException if the input list is null
@@ -45,22 +45,20 @@ public MaxHeap(List<HeapElement> listElements) {
4545

4646
maxHeap = new ArrayList<>();
4747

48-
// Safe initialization: directly add elements first
48+
// Safe initialization: directly add non-null elements first
4949
for (HeapElement heapElement : listElements) {
5050
if (heapElement != null) {
5151
maxHeap.add(heapElement);
52-
} else {
53-
System.out.println("Null element. Not added to heap");
5452
}
5553
}
5654

57-
// Then heapify the array bottom-up
55+
// Heapify the array bottom-up
5856
for (int i = maxHeap.size() / 2; i >= 0; i--) {
5957
heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index
6058
}
6159

6260
if (maxHeap.isEmpty()) {
63-
System.out.println("No element has been added, empty heap.");
61+
throw new IllegalStateException("No valid elements have been added; heap is empty.");
6462
}
6563
}
6664

@@ -180,7 +178,7 @@ private void toggleDown(int elementIndex) {
180178
*/
181179
private HeapElement extractMax() throws EmptyHeapException {
182180
if (maxHeap.isEmpty()) {
183-
throw new EmptyHeapException("Cannot extract from empty heap");
181+
throw new EmptyHeapException("Cannot extract from an empty heap");
184182
}
185183
HeapElement result = maxHeap.getFirst();
186184
deleteElement(1);
@@ -205,7 +203,7 @@ public void insertElement(HeapElement element) {
205203
@Override
206204
public void deleteElement(int elementIndex) throws EmptyHeapException {
207205
if (maxHeap.isEmpty()) {
208-
throw new EmptyHeapException("Cannot delete from empty heap");
206+
throw new EmptyHeapException("Cannot delete from an empty heap");
209207
}
210208
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) {
211209
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]");

0 commit comments

Comments
 (0)