Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.thealgorithms.sorts;

import java.util.PriorityQueue;

/**
* Sorts an array using Java's PriorityQueue (Min-Heap).
*
* <p>Example: Input: [7, 2, 9, 4, 1] Output: [1, 2, 4, 7, 9]
*
* <p>Time Complexity:
* - Inserting n elements into the PriorityQueue → O(n log n)
* - Polling n elements → O(n log n)
* - Total: O(n log n)
*
* <p>Space Complexity: O(n) for the PriorityQueue
*
* @see <a href="https://en.wikipedia.org/wiki/Heap_(data_structure)">
* Heap / PriorityQueue</a>
*/
public final class PriorityQueueSort {

// Private constructor to prevent instantiation (utility class)
private PriorityQueueSort() {
}

/**
* Sorts the given array in ascending order using a PriorityQueue.
*
* @param arr the array to be sorted
* @return the sorted array (in-place)
*/
public static int[] sort(int[] arr) {
if (arr == null || arr.length == 0) {
return arr;
}

PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : arr) {
pq.offer(num);
}

int i = 0;
while (!pq.isEmpty()) {
arr[i++] = pq.poll();
}

return arr;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.thealgorithms.sorts;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import org.junit.jupiter.api.Test;

class PriorityQueueSortTest {

@Test
void testNullArray() {
int[] input = null;
assertArrayEquals(null, PriorityQueueSort.sort(input));
}

@Test
void testSingleElementArray() {
int[] input = {5};
int[] expected = {5};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}

@Test
void testSortNormalArray() {
int[] input = {7, 2, 9, 4, 1};
int[] expected = {1, 2, 4, 7, 9};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}

@Test
void testEmptyArray() {
int[] input = {};
int[] expected = {};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}

@Test
void testNegativeNumbers() {
int[] input = {3, -1, 2, -5, 0};
int[] expected = {-5, -1, 0, 2, 3};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}

@Test
void testAlreadySortedArray() {
int[] input = {1, 2, 3, 4, 5};
int[] expected = {1, 2, 3, 4, 5};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}

@Test
void testArrayWithDuplicates() {
int[] input = {5, 1, 3, 3, 2, 5};
int[] expected = {1, 2, 3, 3, 5, 5};
assertArrayEquals(expected, PriorityQueueSort.sort(input));
}
}