Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- #include <algorithm>
- using namespace std;
- vector<int> sortKSortedArray(const vector<int>& arr, int k) {
- int n = arr.size();
- vector<int> result;
- // Use a min-heap (priority_queue with greater<int>)
- priority_queue<int, vector<int>, greater<int>> minHeap;
- // Insert the first k+1 elements into the heap.
- int heapSize = min(k + 1, n);
- for (int i = 0; i < heapSize; i++) {
- minHeap.push(arr[i]);
- }
- // For the rest of the elements, extract the smallest and then push the next element.
- for (int i = heapSize; i < n; i++) {
- result.push_back(minHeap.top());
- minHeap.pop();
- minHeap.push(arr[i]);
- }
- // Extract any remaining elements in the heap.
- while (!minHeap.empty()) {
- result.push_back(minHeap.top());
- minHeap.pop();
- }
- return result;
- }
- int main() {
- // Read input: first line has n and k.
- int n, k;
- cin >> n >> k;
- vector<int> arr(n);
- for (int i = 0; i < n; i++) {
- cin >> arr[i];
- }
- vector<int> sortedArr = sortKSortedArray(arr, k);
- // Output the sorted array.
- for (int num : sortedArr) {
- cout << num << " ";
- }
- cout << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement