forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kth Element using HEAP (Priority queue).java
80 lines (67 loc) · 1.63 KB
/
Kth Element using HEAP (Priority queue).java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Java code for k largest/ smallest elements in an array
import java.util.*;
class GFG {
// Function to find k largest array element
static void kLargest(int a[], int n, int k)
{
// Implementation using
// a Priority Queue
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>();
for (int i = 0; i < n; ++i) {
// Insert elements into
// the priority queue
pq.add(a[i]);
// If size of the priority
// queue exceeds k
if (pq.size() > k) {
pq.poll();
}
}
// Print the k largest element
while (!pq.isEmpty()) {
System.out.print(pq.peek() + " ");
pq.poll();
}
System.out.println();
}
// Function to find k smallest array element
static void kSmallest(int a[], int n, int k)
{
// Implementation using
// a Priority Queue
PriorityQueue<Integer> pq
= new PriorityQueue<Integer>(
Collections.reverseOrder());
for (int i = 0; i < n; ++i) {
// Insert elements into
// the priority queue
pq.add(a[i]);
// If size of the priority
// queue exceeds k
if (pq.size() > k) {
pq.poll();
}
}
// Print the k largest element
while (!pq.isEmpty()) {
System.out.print(pq.peek() + " ");
pq.poll();
}
}
// Driver Code
public static void main(String[] args)
{
int a[]
= { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
int n = a.length;
int k = 3;
System.out.print(k + " largest elements are : ");
// Function Call
kLargest(a, n, k);
System.out.print(k + " smallest elements are : ");
// Function Call
kSmallest(a, n, k);
}
}
// This code is contributed by Harsh