我正在尝试使用计数选择来实现运行中值算法并且卡住了。
要分析的序列称为“mySequence”,我创建了 2 个全局变量;数据和计数的向量。数据是 mySequence 被一一传输的内容,而 counts 是每个元素的计数。
我担心我可能完全弄错了,或者错过了重要的一步。
#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;
}