使用计数选择 (C++) 运行中位数算法
running median algorithm using counting select (C++)
我正在尝试使用计数选择实现一个正在运行的中位数算法,但卡住了。
要分析的序列称为"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
作为数组索引。
对我来说没有什么突出的,但也许我也忽略了它。
相关文章:
- 在多次运行中获得一致的callgrind输出
- 在 c++ 托管和异步运行中调用 c# 可执行文件
- 在 1.5 秒内找到 3 到 4 个不同整数的中位数超过 2000 万
- 如何修复 OpenMP 程序的 gdb 运行中的线程数
- 十进制的中位数是多少?
- 如何使用第一个、中间和最后一个元素的中位数正确分区?
- 使用 boost::累加器::统计来查找数组的中位数
- 从向量中提取最小值、最大值和中位数的最有效方法是什么
- 如何制作一个为程序的每个运行中存储不同数据类型的向量
- 丢失的数据包仅在第一次运行中发生
- 如果方法是常量,如何找到向量的中位数?
- 在C++中实现两个大小相等的排序数组的中位数
- 统一随机数在所有运行中都是相同的
- 查找一组循环数据的中位数
- 为什么我的中位数快速选择算法segfault
- 是否可以实施中位数的中位数intreselect而没有掉期或堆的分配
- 两个分类阵列的中位数不同
- C++平均值和中位数绝对偏差返回相同的奇怪符号
- 使用计数选择 (C++) 运行中位数算法
- 运行常量大小数组的中位数