From a73e37309613645737e5c3398f318a0921150ec7 Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Thu, 24 Oct 2024 12:25:52 +0530 Subject: [PATCH 01/10] refactor: Enhance docs, add tests in `MaxHeap` --- .../datastructures/heaps/Heap.java | 2 +- .../datastructures/heaps/MaxHeap.java | 184 +++++++++++++----- .../datastructures/heaps/MaxHeapTest.java | 150 ++++++++++++++ 3 files changed, 287 insertions(+), 49 deletions(-) create mode 100644 src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java index 63e101d9b13d..8cb93edf78f3 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java @@ -40,5 +40,5 @@ public interface Heap { * @param elementIndex int containing the position in the heap of the * element to be deleted. */ - void deleteElement(int elementIndex); + void deleteElement(int elementIndex) throws EmptyHeapException; } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 9010aae4cae5..df3397905b69 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -4,16 +4,46 @@ import java.util.List; /** - * Heap tree where a node's key is higher than or equal to its parent's and - * lower than or equal to its children's. + * A Max Heap implementation where each node's key is higher than or equal to its children's keys. + * This data structure provides O(log n) time complexity for insertion and deletion operations, + * and O(1) for retrieving the maximum element. + * + * Properties: + * 1. Complete Binary Tree + * 2. Parent node's key ≥ Children nodes' keys + * 3. Root contains the maximum element + * + * Example usage: + * ```java + * List elements = Arrays.asList( + * new HeapElement(5, "Five"), + * new HeapElement(2, "Two") + * ); + * MaxHeap heap = new MaxHeap(elements); + * heap.insertElement(new HeapElement(7, "Seven")); + * HeapElement max = heap.getElement(); // Returns and removes the maximum element + * ``` * * @author Nicolas Renard + * @author [Your name] (documentation improvements) */ public class MaxHeap implements Heap { + /** The internal list that stores heap elements */ private final List maxHeap; + /** + * Constructs a new MaxHeap from a list of elements. + * Null elements in the input list are ignored with a warning message. + * + * @param listElements List of HeapElement objects to initialize the heap + * @throws IllegalArgumentException if the input list is null + */ public MaxHeap(List listElements) { + if (listElements == null) { + throw new IllegalArgumentException("Input list cannot be null"); + } + maxHeap = new ArrayList<>(); for (HeapElement heapElement : listElements) { if (heapElement != null) { @@ -28,104 +58,162 @@ public MaxHeap(List listElements) { } /** - * Get the element at a given index. The key for the list is equal to index - * value - 1 + * Retrieves the element at the specified index without removing it. + * Note: The index is 1-based for consistency with heap operations. * - * @param elementIndex index - * @return heapElement + * @param elementIndex 1-based index of the element to retrieve + * @return HeapElement at the specified index + * @throws IndexOutOfBoundsException if the index is invalid */ public HeapElement getElement(int elementIndex) { if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) { - throw new IndexOutOfBoundsException("Index out of heap range"); + throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]"); } return maxHeap.get(elementIndex - 1); } - // Get the key of the element at a given index + /** + * Retrieves the key value of an element at the specified index. + * + * @param elementIndex 1-based index of the element + * @return double value representing the key + * @throws IndexOutOfBoundsException if the index is invalid + */ private double getElementKey(int elementIndex) { if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) { - throw new IndexOutOfBoundsException("Index out of heap range"); + throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]"); } - return maxHeap.get(elementIndex - 1).getKey(); } - // Swaps two elements in the heap + /** + * Swaps two elements in the heap. + * + * @param index1 1-based index of first element + * @param index2 1-based index of second element + */ private void swap(int index1, int index2) { HeapElement temporaryElement = maxHeap.get(index1 - 1); maxHeap.set(index1 - 1, maxHeap.get(index2 - 1)); maxHeap.set(index2 - 1, temporaryElement); } - // Toggle an element up to its right place as long as its key is lower than its parent's + /** + * Moves an element up the heap until heap properties are satisfied. + * This operation is called after insertion to maintain heap properties. + * + * @param elementIndex 1-based index of the element to move up + */ private void toggleUp(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - while (getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { + while (elementIndex > 1 && getElementKey((int) Math.floor(elementIndex / 2.0)) < key) { swap(elementIndex, (int) Math.floor(elementIndex / 2.0)); elementIndex = (int) Math.floor(elementIndex / 2.0); } } - // Toggle an element down to its right place as long as its key is higher - // than any of its children's + /** + * Moves an element down the heap until heap properties are satisfied. + * This operation is called after deletion to maintain heap properties. + * + * @param elementIndex 1-based index of the element to move down + */ private void toggleDown(int elementIndex) { double key = maxHeap.get(elementIndex - 1).getKey(); - boolean wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); - while ((2 * elementIndex <= maxHeap.size()) && wrongOrder) { - // Check whether it shall swap the element with its left child or its right one if any. - if ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2))) { - swap(elementIndex, 2 * elementIndex + 1); - elementIndex = 2 * elementIndex + 1; + boolean wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1)); + + while (2 * elementIndex <= maxHeap.size() && wrongOrder) { + int largerChildIndex; + if (2 * elementIndex + 1 <= maxHeap.size() && getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2)) { + largerChildIndex = 2 * elementIndex + 1; } else { - swap(elementIndex, 2 * elementIndex); - elementIndex = 2 * elementIndex; + largerChildIndex = 2 * elementIndex; } - wrongOrder = (key < getElementKey(elementIndex * 2)) || (key < getElementKey(Math.min(elementIndex * 2, maxHeap.size()))); + + swap(elementIndex, largerChildIndex); + elementIndex = largerChildIndex; + + wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1)); } } - private HeapElement extractMax() { + /** + * Extracts and returns the maximum element from the heap. + * + * @return HeapElement with the highest key + * @throws EmptyHeapException if the heap is empty + */ + private HeapElement extractMax() throws EmptyHeapException { + if (maxHeap.isEmpty()) { + throw new EmptyHeapException("Cannot extract from empty heap"); + } HeapElement result = maxHeap.get(0); - deleteElement(0); + deleteElement(1); return result; } + /** + * {@inheritDoc} + */ @Override - public final void insertElement(HeapElement element) { + public void insertElement(HeapElement element) { + if (element == null) { + throw new IllegalArgumentException("Cannot insert null element"); + } maxHeap.add(element); toggleUp(maxHeap.size()); } + /** + * {@inheritDoc} + */ @Override - public void deleteElement(int elementIndex) { + public void deleteElement(int elementIndex) throws EmptyHeapException { if (maxHeap.isEmpty()) { - try { - throw new EmptyHeapException("Attempt to delete an element from an empty heap"); - } catch (EmptyHeapException e) { - e.printStackTrace(); - } + throw new EmptyHeapException("Cannot delete from empty heap"); } if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) { - throw new IndexOutOfBoundsException("Index out of heap range"); + throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]"); } - // The last element in heap replaces the one to be deleted - maxHeap.set(elementIndex - 1, getElement(maxHeap.size())); - maxHeap.remove(maxHeap.size()); - // Shall the new element be moved up... - if (getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) { - toggleUp(elementIndex); - } // ... or down ? - else if (((2 * elementIndex <= maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2))) || ((2 * elementIndex < maxHeap.size()) && (getElementKey(elementIndex) < getElementKey(elementIndex * 2)))) { - toggleDown(elementIndex); + + // Replace with last element and remove last position + maxHeap.set(elementIndex - 1, maxHeap.get(maxHeap.size() - 1)); + maxHeap.remove(maxHeap.size() - 1); + + // No need to toggle if we just removed the last element + if (!maxHeap.isEmpty() && elementIndex <= maxHeap.size()) { + // Determine whether to toggle up or down + if (elementIndex > 1 && getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) { + toggleUp(elementIndex); + } else { + toggleDown(elementIndex); + } } } + /** + * {@inheritDoc} + */ @Override public HeapElement getElement() throws EmptyHeapException { - try { - return extractMax(); - } catch (Exception e) { - throw new EmptyHeapException("Heap is empty. Error retrieving element", e); - } + return extractMax(); + } + + /** + * Returns the current size of the heap. + * + * @return number of elements in the heap + */ + public int size() { + return maxHeap.size(); + } + + /** + * Checks if the heap is empty. + * + * @return true if the heap contains no elements + */ + public boolean isEmpty() { + return maxHeap.isEmpty(); } } diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java new file mode 100644 index 000000000000..bda19015b81b --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java @@ -0,0 +1,150 @@ +package com.thealgorithms.datastructures.heaps; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeEach; +import static org.junit.jupiter.api.Assertions.*; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.List; + +/** + * Unit tests for MaxHeap implementation + */ +class MaxHeapTest { + + private MaxHeap heap; + + @BeforeEach + void setUp() { + // Create a fresh heap for each test + List elements = Arrays.asList( + new HeapElement(5.0, "Five"), + new HeapElement(2.0, "Two"), + new HeapElement(8.0, "Eight"), + new HeapElement(1.0, "One"), + new HeapElement(9.0, "Nine") + ); + heap = new MaxHeap(elements); + } + + @Test + void testConstructorWithNullList() { + assertThrows(IllegalArgumentException.class, () -> new MaxHeap(null)); + } + + @Test + void testConstructorWithEmptyList() { + MaxHeap emptyHeap = new MaxHeap(new ArrayList<>()); + assertTrue(emptyHeap.isEmpty()); + } + + @Test + void testConstructorWithNullElements() { + List elements = Arrays.asList( + new HeapElement(1.0, "One"), + null, + new HeapElement(2.0, "Two") + ); + MaxHeap heap = new MaxHeap(elements); + assertEquals(2, heap.size()); + } + + @Test + void testInsertElement() { + heap.insertElement(new HeapElement(10.0, "Ten")); + assertEquals(10.0, heap.getElement(1).getKey()); + assertEquals(6, heap.size()); + } + + @Test + void testInsertNullElement() { + assertThrows(IllegalArgumentException.class, () -> heap.insertElement(null)); + } + + @Test + void testGetElementAtIndex() { + HeapElement element = heap.getElement(1); + assertEquals(9.0, element.getKey()); + assertEquals("Nine", element.getValue()); + } + + @Test + void testGetElementAtInvalidIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(0)); + assertThrows(IndexOutOfBoundsException.class, () -> heap.getElement(10)); + } + + @Test + void testDeleteElement() { + heap.deleteElement(1); + assertEquals(8.0, heap.getElement(1).getKey()); + assertEquals(4, heap.size()); + } + + @Test + void testDeleteElementAtInvalidIndex() { + assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(0)); + assertThrows(IndexOutOfBoundsException.class, () -> heap.deleteElement(10)); + } + + @Test + void testDeleteFromEmptyHeap() { + MaxHeap emptyHeap = new MaxHeap(new ArrayList<>()); + assertThrows(EmptyHeapException.class, () -> emptyHeap.deleteElement(1)); + } + + @Test + void testExtractMax() throws EmptyHeapException { + HeapElement max = heap.getElement(); + assertEquals(9.0, max.getKey()); + assertEquals("Nine", max.getValue()); + assertEquals(4, heap.size()); + + max = heap.getElement(); + assertEquals(8.0, max.getKey()); + assertEquals(3, heap.size()); + } + + @Test + void testExtractMaxFromEmptyHeap() { + MaxHeap emptyHeap = new MaxHeap(new ArrayList<>()); + assertThrows(EmptyHeapException.class, () -> emptyHeap.getElement()); + } + + @Test + void testHeapOrder() { + // Test that parent is always greater than or equal to children + for (int i = 1; i <= heap.size() / 2; i++) { + double parentKey = heap.getElement(i).getKey(); + + // Check left child + if (2 * i <= heap.size()) { + assertTrue(parentKey >= heap.getElement(2 * i).getKey()); + } + + // Check right child + if (2 * i + 1 <= heap.size()) { + assertTrue(parentKey >= heap.getElement(2 * i + 1).getKey()); + } + } + } + + @Test + void testSizeAndEmpty() { + assertEquals(5, heap.size()); + assertFalse(heap.isEmpty()); + + // Remove all elements + while (!heap.isEmpty()) { + try { + heap.getElement(); + } catch (EmptyHeapException e) { + fail("Should not throw EmptyHeapException while heap is not empty"); + } + } + + assertEquals(0, heap.size()); + assertTrue(heap.isEmpty()); + } +} From 28338e53a36fd77781acfd7c626451e66f1b6970 Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Thu, 24 Oct 2024 12:30:03 +0530 Subject: [PATCH 02/10] Fix --- .../datastructures/heaps/HeapElement.java | 6 ++- .../datastructures/heaps/MaxHeap.java | 44 +++++++++++++++++-- .../datastructures/heaps/MaxHeapTest.java | 30 +++++-------- 3 files changed, 57 insertions(+), 23 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java index 7c457a340645..9408e13a2c6b 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java @@ -111,7 +111,7 @@ public String toString() { } /** - * @param otherHeapElement + * @param o : an object to compare with the current element * @return true if the keys on both elements are identical and the * additional info objects are identical. */ @@ -134,4 +134,8 @@ public int hashCode() { result = 31 * result + (additionalInfo != null ? additionalInfo.hashCode() : 0); return result; } + + public String getValue() { + return additionalInfo.toString(); + } } diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index df3397905b69..d7f399f6c04d 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -45,18 +45,54 @@ public MaxHeap(List listElements) { } maxHeap = new ArrayList<>(); + + // Safe initialization: directly add elements first for (HeapElement heapElement : listElements) { if (heapElement != null) { - insertElement(heapElement); + maxHeap.add(heapElement); } else { System.out.println("Null element. Not added to heap"); } } + + // Then heapify the array bottom-up + for (int i = maxHeap.size() / 2; i >= 0; i--) { + heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index + } + if (maxHeap.isEmpty()) { System.out.println("No element has been added, empty heap."); } } + /** + * Maintains heap properties by moving an element down the heap. + * Similar to toggleDown but used specifically during initialization. + * + * @param elementIndex 1-based index of the element to heapify + */ + private void heapifyDown(int elementIndex) { + int largest = elementIndex - 1; + int leftChild = 2 * elementIndex - 1; + int rightChild = 2 * elementIndex; + + if (leftChild < maxHeap.size() && maxHeap.get(leftChild).getKey() > maxHeap.get(largest).getKey()) { + largest = leftChild; + } + + if (rightChild < maxHeap.size() && maxHeap.get(rightChild).getKey() > maxHeap.get(largest).getKey()) { + largest = rightChild; + } + + if (largest != elementIndex - 1) { + HeapElement swap = maxHeap.get(elementIndex - 1); + maxHeap.set(elementIndex - 1, maxHeap.get(largest)); + maxHeap.set(largest, swap); + + heapifyDown(largest + 1); + } + } + /** * Retrieves the element at the specified index without removing it. * Note: The index is 1-based for consistency with heap operations. @@ -147,7 +183,7 @@ private HeapElement extractMax() throws EmptyHeapException { if (maxHeap.isEmpty()) { throw new EmptyHeapException("Cannot extract from empty heap"); } - HeapElement result = maxHeap.get(0); + HeapElement result = maxHeap.getFirst(); deleteElement(1); return result; } @@ -177,8 +213,8 @@ public void deleteElement(int elementIndex) throws EmptyHeapException { } // Replace with last element and remove last position - maxHeap.set(elementIndex - 1, maxHeap.get(maxHeap.size() - 1)); - maxHeap.remove(maxHeap.size() - 1); + maxHeap.set(elementIndex - 1, maxHeap.getLast()); + maxHeap.removeLast(); // No need to toggle if we just removed the last element if (!maxHeap.isEmpty() && elementIndex <= maxHeap.size()) { diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java index bda19015b81b..c1b7eb3fd4ae 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java @@ -1,12 +1,16 @@ package com.thealgorithms.datastructures.heaps; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.BeforeEach; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; -import java.util.Arrays; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * Unit tests for MaxHeap implementation @@ -18,13 +22,7 @@ class MaxHeapTest { @BeforeEach void setUp() { // Create a fresh heap for each test - List elements = Arrays.asList( - new HeapElement(5.0, "Five"), - new HeapElement(2.0, "Two"), - new HeapElement(8.0, "Eight"), - new HeapElement(1.0, "One"), - new HeapElement(9.0, "Nine") - ); + List elements = Arrays.asList(new HeapElement(5.0, "Five"), new HeapElement(2.0, "Two"), new HeapElement(8.0, "Eight"), new HeapElement(1.0, "One"), new HeapElement(9.0, "Nine")); heap = new MaxHeap(elements); } @@ -41,11 +39,7 @@ void testConstructorWithEmptyList() { @Test void testConstructorWithNullElements() { - List elements = Arrays.asList( - new HeapElement(1.0, "One"), - null, - new HeapElement(2.0, "Two") - ); + List elements = Arrays.asList(new HeapElement(1.0, "One"), null, new HeapElement(2.0, "Two")); MaxHeap heap = new MaxHeap(elements); assertEquals(2, heap.size()); } @@ -76,7 +70,7 @@ void testGetElementAtInvalidIndex() { } @Test - void testDeleteElement() { + void testDeleteElement() throws EmptyHeapException { heap.deleteElement(1); assertEquals(8.0, heap.getElement(1).getKey()); assertEquals(4, heap.size()); @@ -140,7 +134,7 @@ void testSizeAndEmpty() { try { heap.getElement(); } catch (EmptyHeapException e) { - fail("Should not throw EmptyHeapException while heap is not empty"); + Assertions.fail("Should not throw EmptyHeapException while heap is not empty"); } } From 0ec00919067e7d39f110b0b6621afec465741900 Mon Sep 17 00:00:00 2001 From: Hardvan Date: Thu, 24 Oct 2024 07:00:24 +0000 Subject: [PATCH 03/10] Update directory --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 1def3e25c064..0a6bc2c83d5c 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -827,6 +827,7 @@ * heaps * [FibonacciHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/FibonacciHeapTest.java) * [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java) + * [MaxHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java) * lists * [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java) * [CreateAndDetectLoopTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoopTest.java) From 7b95a5503a0243ee7b030814dd507fb54461dcd0 Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Thu, 24 Oct 2024 12:31:23 +0530 Subject: [PATCH 04/10] Fix --- .../java/com/thealgorithms/datastructures/heaps/MaxHeap.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index d7f399f6c04d..3aa8e0a36a36 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -25,7 +25,6 @@ * ``` * * @author Nicolas Renard - * @author [Your name] (documentation improvements) */ public class MaxHeap implements Heap { From 275cb2b9ec8dc071e67c1ae35bb185395bc6b6be Mon Sep 17 00:00:00 2001 From: Hardvan Date: Sat, 26 Oct 2024 06:22:35 +0000 Subject: [PATCH 05/10] Update directory --- DIRECTORY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 179bc96c3421..6dbd2fe961da 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -836,6 +836,7 @@ * [GenericHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/GenericHeapTest.java) * [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java) * [MaxHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java) + * [MinPriorityQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java) * lists * [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java) * [CountSinglyLinkedListRecursionTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursionTest.java) From 575ce6d482539f4776c660103ae37bb53ede9758 Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Tue, 29 Oct 2024 09:45:10 +0530 Subject: [PATCH 06/10] Fix --- .../datastructures/heaps/MaxHeap.java | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 3aa8e0a36a36..0c356fc47130 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -33,7 +33,7 @@ public class MaxHeap implements Heap { /** * Constructs a new MaxHeap from a list of elements. - * Null elements in the input list are ignored with a warning message. + * Null elements in the input list are ignored. * * @param listElements List of HeapElement objects to initialize the heap * @throws IllegalArgumentException if the input list is null @@ -45,22 +45,20 @@ public MaxHeap(List listElements) { maxHeap = new ArrayList<>(); - // Safe initialization: directly add elements first + // Safe initialization: directly add non-null elements first for (HeapElement heapElement : listElements) { if (heapElement != null) { maxHeap.add(heapElement); - } else { - System.out.println("Null element. Not added to heap"); } } - // Then heapify the array bottom-up + // Heapify the array bottom-up for (int i = maxHeap.size() / 2; i >= 0; i--) { heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index } if (maxHeap.isEmpty()) { - System.out.println("No element has been added, empty heap."); + throw new IllegalStateException("No valid elements have been added; heap is empty."); } } @@ -180,7 +178,7 @@ private void toggleDown(int elementIndex) { */ private HeapElement extractMax() throws EmptyHeapException { if (maxHeap.isEmpty()) { - throw new EmptyHeapException("Cannot extract from empty heap"); + throw new EmptyHeapException("Cannot extract from an empty heap"); } HeapElement result = maxHeap.getFirst(); deleteElement(1); @@ -205,7 +203,7 @@ public void insertElement(HeapElement element) { @Override public void deleteElement(int elementIndex) throws EmptyHeapException { if (maxHeap.isEmpty()) { - throw new EmptyHeapException("Cannot delete from empty heap"); + throw new EmptyHeapException("Cannot delete from an empty heap"); } if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) { throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]"); From 63adc3e1a1f02ccf32424ee2409a1f210b414b0b Mon Sep 17 00:00:00 2001 From: Hardvan Date: Tue, 29 Oct 2024 04:16:14 +0000 Subject: [PATCH 07/10] Update directory --- DIRECTORY.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index aacc8120b538..ac4e2e8f5a7a 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -597,6 +597,7 @@ * [UnionFind](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/UnionFind.java) * [UpperBound](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/searches/UpperBound.java) * slidingwindow + * [LongestSubarrayWithSumLessOrEqualToK](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java) * [LongestSubstringWithoutRepeatingCharacters](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharacters.java) * [MaxSumKSizeSubarray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarray.java) * [MinSumKSizeSubarray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarray.java) @@ -874,6 +875,9 @@ * [KthElementFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/KthElementFinderTest.java) * [LeftistHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/LeftistHeapTest.java) * [MaxHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MaxHeapTest.java) + * [MedianFinderTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MedianFinderTest.java) + * [MergeKSortedArraysTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MergeKSortedArraysTest.java) + * [MinHeapTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MinHeapTest.java) * [MinPriorityQueueTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java) * lists * [CircleLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/datastructures/lists/CircleLinkedListTest.java) @@ -1226,6 +1230,7 @@ * [UnionFindTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/UnionFindTest.java) * [UpperBoundTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/UpperBoundTest.java) * slidingwindow + * [LongestSubarrayWithSumLessOrEqualToKTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToKTest.java) * [LongestSubstringWithoutRepeatingCharactersTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java) * [MaxSumKSizeSubarrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java) * [MinSumKSizeSubarrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java) From 7358bba6ee4194209e876d664dae0b488a114e5d Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Tue, 29 Oct 2024 09:46:56 +0530 Subject: [PATCH 08/10] Fix --- .../java/com/thealgorithms/datastructures/heaps/MaxHeap.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 0c356fc47130..2c07a1d29873 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -14,7 +14,7 @@ * 3. Root contains the maximum element * * Example usage: - * ```java + *
  * List elements = Arrays.asList(
  *     new HeapElement(5, "Five"),
  *     new HeapElement(2, "Two")
@@ -22,7 +22,7 @@
  * MaxHeap heap = new MaxHeap(elements);
  * heap.insertElement(new HeapElement(7, "Seven"));
  * HeapElement max = heap.getElement(); // Returns and removes the maximum element
- * ```
+ * 
* * @author Nicolas Renard */ From 363d805cf496b001bec4c506b5f10bc7f7ed5230 Mon Sep 17 00:00:00 2001 From: Hardik Pawar Date: Tue, 29 Oct 2024 09:51:26 +0530 Subject: [PATCH 09/10] Fix --- .../java/com/thealgorithms/datastructures/heaps/MaxHeap.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java index 2c07a1d29873..5b4b29cf1c2d 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java @@ -56,10 +56,6 @@ public MaxHeap(List listElements) { for (int i = maxHeap.size() / 2; i >= 0; i--) { heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index } - - if (maxHeap.isEmpty()) { - throw new IllegalStateException("No valid elements have been added; heap is empty."); - } } /** From 40d1ccbca506c39c0d549295f4fb55aa94fe67c9 Mon Sep 17 00:00:00 2001 From: siriak Date: Tue, 29 Oct 2024 20:41:46 +0000 Subject: [PATCH 10/10] Update directory --- DIRECTORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/DIRECTORY.md b/DIRECTORY.md index 0e3415bf2c26..01e031b58581 100644 --- a/DIRECTORY.md +++ b/DIRECTORY.md @@ -488,6 +488,7 @@ * [PalindromePrime](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/PalindromePrime.java) * [PalindromeSinglyLinkedList](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java) * [RangeInSortedArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java) + * [ShuffleArray](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ShuffleArray.java) * [Sparsity](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/Sparsity.java) * [ThreeSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/ThreeSumProblem.java) * [TwoSumProblem](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/misc/TwoSumProblem.java) @@ -1137,6 +1138,7 @@ * [PalindromePrimeTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/PalindromePrimeTest.java) * [PalindromeSinglyLinkedListTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/PalindromeSinglyLinkedListTest.java) * [RangeInSortedArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/RangeInSortedArrayTest.java) + * [ShuffleArrayTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/ShuffleArrayTest.java) * [SparsityTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/SparsityTest.java) * [ThreeSumProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/ThreeSumProblemTest.java) * [TwoSumProblemTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java)