-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.java
More file actions
41 lines (37 loc) · 1.21 KB
/
HeapSort.java
File metadata and controls
41 lines (37 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Arrays;
import java.util.Queue;
import java.util.PriorityQueue;
/**
*
* Implementation: Using a priority queue is a convenient
* data structure to implement heap sort
*
* Time Complexity - O(nlogn)
* - O(logn) time to add and remove elements
* - O(n) time since loop runs n times
*/
public class HeapSort {
/******************** First HeapSort Implementation ********************/
public void heapSort(int[] arr){
Queue<Integer> pq = new PriorityQueue<>();
Arrays.stream(arr).forEach(element -> pq.add(element));
StringBuilder str = new StringBuilder("[");
for(int k=0; pq.size() > 0; k++){
if(k > 0) { str.append(", "); }
str.append(pq.poll());
}
str.append("]");
System.out.printf(str.toString());
}
public <E> void heapSort(E[] arr){
Queue<E> pq = new PriorityQueue<>();
Arrays.stream(arr).forEach(element -> pq.add(element));
StringBuilder str = new StringBuilder("[");
for(int k=0; pq.size() > 0; k++){
if(k > 0) { str.append(", "); }
str.append(pq.poll());
}
str.append("]");
System.out.printf(str.toString());
}
}