I am implementing k sorted array using priority queue in C++. In the output, only the first k elements are sorted but rest are not. Please find the problem in the code.
Here is the code:
#include <iostream>
#include <queue>
using namespace std;
void kSortedArray(int input[], int n, int k){
priority_queue<int> pq;
for(int i= 0; i < k; i++){
pq.push(input[i]);
}
int j = 0;
for(int i = k; i < n; i++){
int ans = pq.top();
pq.pop();
input[j] = ans;
pq.push(input[i]);
j++;
}
while(pq.size() != 0){
input[j] = pq.top();
pq.pop();
}
}
int main() {
int input[] = {10, 12, 6, 7, 9};
int k = 3;
kSortedArray(input, 5, k);
for(int i = 0; i < 5; i++){
cout << input[i] << " ";
}
}
Correct this part (you forgot to increment j
):
while(pq.size() != 0){
input[j++] = pq.top(); // <-- this line
pq.pop();
}
Also your code sorts in decreasing order. If you want to sort in an increasing order, use a minheap:
priority_queue<int,vector<int>, greater<int>> pq;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.