繁体   English   中英

使用优先级队列的 K 排序数组 - C++

[英]K sorted array using priority queue - C++

我正在使用 C++ 中的优先级队列实现 k 排序数组。 在 output 中,只有前 k 个元素被排序,但 rest 没有。 请在代码中找到问题。

这是代码:

#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] << " ";
    }
}

更正这部分(您忘记增加j ):

    while(pq.size() != 0){
        input[j++] = pq.top(); // <-- this line
        pq.pop();
    }

您的代码也按降序排序。 如果要按升序排序,请使用 minheap:

priority_queue<int,vector<int>, greater<int>> pq;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM