- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAlmostKSorted.java
More file actions
Latest commit
31 lines (26 loc) · 652 Bytes
/
Copy pathAlmostKSorted.java
File metadata and controls
31 lines (26 loc) · 652 Bytes
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
packagecom.bhatt.codechef;
importjava.util.Arrays;
importjava.util.PriorityQueue;
publicclassAlmostKSorted{
publicstaticvoidmain(Stringargs[]){
int[] arr = {17, 5, 18, 1, 4, 5};
System.out.println(Arrays.toString(sort(arr, 4)));
}
publicstaticint[] sort(int[] arr, intk){
PriorityQueue<Integer> pq = newPriorityQueue<Integer>(k);
int[] result = newint[arr.length];
intcount = 0;
for(inti = 0; i < arr.length; i++){
pq.add(arr[i]);
if(pq.size() == k){
result[count++] = pq.peek();
pq.remove();
}
}
while(!pq.isEmpty()){
result[count++]=pq.peek();
pq.remove();
}
returnresult;
}
}