Skip to content

Commit c1a7f8d

Browse files
authored
fix(heaps): prevent premature termination and return sorted array in MinPriorityQueue.heapSort (#7765)
fix(heaps): prevent premature loop termination and return sorted elements in MinPriorityQueue.heapSort
1 parent e79b0f1 commit c1a7f8d

2 files changed

Lines changed: 20 additions & 9 deletions

File tree

‎src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,17 @@ public void print() {
100100
}
101101

102102
/**
103-
* Sorts the elements in the queue using heap sort.
103+
* Sorts and returns the elements in the queue in ascending order using heap sort.
104+
*
105+
* @return an array containing all elements sorted in ascending order
104106
*/
105-
public void heapSort() {
106-
for (int i = 1; i <= this.size; i++) {
107-
this.delete();
107+
public int[] heapSort() {
108+
int initialSize = this.size;
109+
int[] sorted = new int[initialSize];
110+
for (int i = 0; i < initialSize; i++) {
111+
sorted[i] = this.delete();
108112
}
113+
return sorted;
109114
}
110115

111116
/**

‎src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,19 @@ void testHeapSort() {
5555
queue.insert(1);
5656
queue.insert(3);
5757

58-
// Delete all elements to sort the queue
59-
int[] sortedArray = new int[5];
60-
for (int i = 0; i < 5; i++) {
61-
sortedArray[i] = queue.delete();
62-
}
58+
int[] sortedArray = queue.heapSort();
6359

6460
Assertions.assertArrayEquals(new int[] {1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order.");
61+
Assertions.assertTrue(queue.isEmpty(), "The queue should be empty after heap sort.");
62+
}
63+
64+
@Test
65+
void testHeapSortEmptyQueue() {
66+
MinPriorityQueue queue = new MinPriorityQueue(5);
67+
int[] sortedArray = queue.heapSort();
68+
69+
Assertions.assertEquals(0, sortedArray.length, "Sorting an empty queue should return an empty array.");
70+
Assertions.assertTrue(queue.isEmpty(), "The queue should remain empty.");
6571
}
6672

6773
@Test

0 commit comments

Comments
 (0)