Skip to content

Commit 3145732

Browse files
authored
Added PriorityQueueSort.java
Implemented PriorityQueueSort using Java's PriorityQueue (Min-Heap). - Returns the array sorted in ascending order - Time complexity: O(n log n) - Space complexity: O(n)
1 parent 85a2df4 commit 3145732

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.PriorityQueue;
4+
5+
/**
6+
* Sorts an array using Java's PriorityQueue (Min-Heap).
7+
*
8+
* <p>Example:
9+
* Input: [7, 2, 9, 4, 1]
10+
* Output: [1, 2, 4, 7, 9]
11+
*
12+
* <p>Time Complexity:
13+
* - Inserting n elements into the PriorityQueue → O(n log n)
14+
* - Polling n elements → O(n log n)
15+
* - Total: O(n log n)
16+
*
17+
* Space Complexity: O(n) for the PriorityQueue
18+
*/
19+
public class PriorityQueueSort {
20+
21+
/**
22+
* Sorts the given array in ascending order using a PriorityQueue.
23+
*
24+
* @param arr the array to be sorted
25+
* @return the sorted array (in-place)
26+
*/
27+
public static int[] sort(int[] arr) {
28+
if (arr == null || arr.length == 0) {
29+
return arr;
30+
}
31+
32+
PriorityQueue<Integer> pq = new PriorityQueue<>();
33+
for (int num : arr) {
34+
pq.offer(num);
35+
}
36+
37+
int i = 0;
38+
while (!pq.isEmpty()) {
39+
arr[i++] = pq.poll();
40+
}
41+
42+
return arr;
43+
}
44+
}

0 commit comments

Comments
 (0)