63 lines
1.2 KiB
C++
63 lines
1.2 KiB
C++
/*
|
||
* © Copyright 2014 – Urheberrechtshinweis
|
||
* Alle Rechte vorbehalten / All Rights Reserved
|
||
*
|
||
* Programmcode ist urheberrechtlich geschuetzt.
|
||
* Das Urheberrecht liegt, soweit nicht ausdruecklich anders gekennzeichnet, bei Frank Ebner.
|
||
* Keine Verwendung ohne explizite Genehmigung.
|
||
* (vgl. § 106 ff UrhG / § 97 UrhG)
|
||
*/
|
||
|
||
#ifndef STATS_MEDIAN_H
|
||
#define STATS_MEDIAN_H
|
||
|
||
#include <vector>
|
||
#include <algorithm>
|
||
|
||
#include "../../Assertions.h"
|
||
|
||
namespace Stats {
|
||
|
||
template <typename Scalar> class Median {
|
||
|
||
private:
|
||
|
||
/** all scalar values in a sorted order (ascending) */
|
||
std::vector<Scalar> sorted;
|
||
|
||
public:
|
||
|
||
/** add the given scalar value to the median calculation */
|
||
void add(const Scalar value) {
|
||
|
||
const auto idx = std::upper_bound( sorted.begin(), sorted.end(), value );
|
||
sorted.insert( idx, value );
|
||
|
||
}
|
||
|
||
/** get the median of all added values */
|
||
Scalar get() const {
|
||
|
||
// sanity check
|
||
Assert::isNot0(sorted.size(), "add elements first!");
|
||
|
||
if (sorted.size() % 2 == 1) { // odd
|
||
|
||
const int idx = sorted.size()/2;
|
||
return sorted[idx];
|
||
|
||
} else { // even
|
||
|
||
const int idx0 = sorted.size()/2 - 1;
|
||
return (sorted[idx0] + sorted[idx0+1]) / 2;
|
||
|
||
}
|
||
|
||
}
|
||
|
||
};
|
||
|
||
}
|
||
|
||
#endif // STATS_MEDIAN_H
|