Tuesday, April 19, 2022

Sort K-sorted Array

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

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...