Advertisement
aqibm

Untitled

Apr 5th, 2025
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6.  
  7. vector<int> sortKSortedArray(const vector<int>& arr, int k) {
  8. int n = arr.size();
  9. vector<int> result;
  10.  
  11. // Use a min-heap (priority_queue with greater<int>)
  12. priority_queue<int, vector<int>, greater<int>> minHeap;
  13.  
  14. // Insert the first k+1 elements into the heap.
  15. int heapSize = min(k + 1, n);
  16. for (int i = 0; i < heapSize; i++) {
  17. minHeap.push(arr[i]);
  18. }
  19.  
  20. // For the rest of the elements, extract the smallest and then push the next element.
  21. for (int i = heapSize; i < n; i++) {
  22. result.push_back(minHeap.top());
  23. minHeap.pop();
  24. minHeap.push(arr[i]);
  25. }
  26.  
  27. // Extract any remaining elements in the heap.
  28. while (!minHeap.empty()) {
  29. result.push_back(minHeap.top());
  30. minHeap.pop();
  31. }
  32.  
  33. return result;
  34. }
  35.  
  36. int main() {
  37. // Read input: first line has n and k.
  38. int n, k;
  39. cin >> n >> k;
  40. vector<int> arr(n);
  41. for (int i = 0; i < n; i++) {
  42. cin >> arr[i];
  43. }
  44.  
  45. vector<int> sortedArr = sortKSortedArray(arr, k);
  46.  
  47. // Output the sorted array.
  48. for (int num : sortedArr) {
  49. cout << num << " ";
  50. }
  51. cout << endl;
  52.  
  53. return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement