diff --git a/src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java b/src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java new file mode 100644 index 000000000000..16f13050e8b3 --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/PriorityQueueSort.java @@ -0,0 +1,49 @@ +package com.thealgorithms.sorts; + +import java.util.PriorityQueue; + +/** + * Sorts an array using Java's PriorityQueue (Min-Heap). + * + *

Example: Input: [7, 2, 9, 4, 1] Output: [1, 2, 4, 7, 9] + * + *

Time Complexity: + * - Inserting n elements into the PriorityQueue → O(n log n) + * - Polling n elements → O(n log n) + * - Total: O(n log n) + * + *

Space Complexity: O(n) for the PriorityQueue + * + * @see + * Heap / PriorityQueue + */ +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 pq = new PriorityQueue<>(); + for (int num : arr) { + pq.offer(num); + } + + int i = 0; + while (!pq.isEmpty()) { + arr[i++] = pq.poll(); + } + + return arr; + } +} diff --git a/src/test/java/com/thealgorithms/sorts/PriorityQueueSortTest.java b/src/test/java/com/thealgorithms/sorts/PriorityQueueSortTest.java new file mode 100644 index 000000000000..215431293227 --- /dev/null +++ b/src/test/java/com/thealgorithms/sorts/PriorityQueueSortTest.java @@ -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)); + } +}