1. The array is nearly sorted. Every element is at-max displaced k spots left or right to it's position in the sorted array. Hence it is being called k-sorted array.
2. You are required to sort and print the sorted array.
package pep.Day65;
import java.util.PriorityQueue;
public class Sort_K_sorted_Array {
public static void main(String[] args) {
int[] arr = new int[]{3, 2, 4, 1, 6, 5, 7, 9, 8, 3};
int k = 3;
PriorityQueue<Integer> pq = new PriorityQueue<>();
// <= k islea aaya kyon ki, 0th spot pr upto kth index
// tak ke bande aa skte hain
for (int i = 0; i <= k; i++) {
pq.add(arr[i]);
}
for (int i = k + 1; i < arr.length; i++) {
System.out.print(pq.remove() + " ");
pq.add(arr[i]);
}
while (pq.size() > 0)
System.out.print(pq.remove() + " ");
}
}
No comments:
Post a Comment