使用计数选择 (C++) 运行中位数算法

running median algorithm using counting select (C++)

本文关键字:运行 中位数 算法 C++ 选择      更新时间:2023-10-16

我正在尝试使用计数选择实现一个正在运行的中位数算法,但卡住了。

要分析的序列称为"mySequence",我创建了 2 个全局变量:数据和计数的向量。数据是 mySequence 逐个传输到的内容,计数是每个元素的计数。

担心我可能完全错了,或者错过了重要的一步。

#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
int maximum = 0;
vector<int> data;
vector<int> counts;
vector<int>::iterator it;
/*
 * A Program that calculates and outputs the running median of a sequence of values
 */
/////////////////////////////////////////////////////////////////////////////
// This function prints the running median of a sequence of values past to it
/////////////////////////////////////////////////////////////////////////////
void runningMedian(int element, int k) { // vector<int> &data
    maximum = data.size(); // finds how many data elements are to be processed  
    for (int i = 0; i <= maximum; i++) // this creates the counts for each element
    {
        counts[element] += 1;
    }
    int c = 0;
    while (k >= 0) {
        k -= counts[c++];
        }
    cout << c - 1;
}
/////////////////////////////////////////////////////////////////
// This main function uses test data to test the above functions
/////////////////////////////////////////////////////////////////
int main(int argc, char** argv) {
    int mySequence [] = {7, 9, 3, 8, 0, 2, 4, 8, 3, 9}; // test sequence
    for (int i = 1; i <= 10; i++) counts.push_back(0); // This initialises the counts vector all to 0
    /// prints out the sequence of the data ///
    cout << "Sequence: ";
    for (int i = 0; i < 10; i++) {
        cout << mySequence[i] << " ";
    }
    cout << endl;
    /// /// /// /// ///

    cout << "Running Medians: ";
    for (int i = 0; i < 10; i++) {
        data.push_back(mySequence[i]); // puts sequence into vector 1 by 1
        runningMedian(mySequence[i], (data.size() / 2));
        cout << " ";
    }
    return 0;
}

看起来像一个错误:

void runningMedian(int element, int k) { // vector<int> &data
    maximum = data.size(); // finds how many data elements are to be processed  
    for (int i = 0; i <= maximum; i++) // this creates the counts for each element
    {
        counts[element] += 1;
    }

当我看到一个for循环迭代i=0; i<= ...时,我会担心 - 它实际上会迭代maximum+1次,而不是maximum次。(惯用语是i=0; i< ...。这通常是缓冲区溢出或未初始化内存访问的快速途径 - 但由于在这种情况下您甚至没有使用i,因此它不会产生这种影响。我想你的意思是i而不是element——否则为什么还要打扰循环呢?这可以在没有循环的情况下重写,如下所示:

counts[element] += (maximum + 1);

(你可以看到为什么我认为你可能打算使用 i 作为数组索引。

对我来说没有什么突出的,但也许我也忽略了它。