#include <iostream>
#include <queue>
class RealTimeMedianCalculator {
private:
std::priority_queue<int> maxHeap; // Stores the smaller half of the numbers
std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap; // Stores the larger half of the numbers
public:
void processInput(int number) {
if (maxHeap.empty() || number <= maxHeap.top()) {
maxHeap.push(number);
} else {
minHeap.push(number);
}
// Balance the heaps
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.push(maxHeap.top());
maxHeap.pop();
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
double median;
if (maxHeap.size() == minHeap.size()) {
median = (static_cast<double>(maxHeap.top()) + minHeap.top()) / 2.0;
} else {
median = static_cast<double>(maxHeap.top());
}
std::cout << "Median up to now: " << median << std::endl;
}
};
int main() {
RealTimeMedianCalculator calculator;
std::cout << "Enter integers (type 'exit' to stop):" << std::endl;
while (true) {
std::string input;
std::cin >> input;
if (input == "exit") {
break;
}
try {
int number = std::stoi(input);
calculator.processInput(number);
} catch (const std::invalid_argument& e) {
std::cout << "Invalid input. Please enter an integer or type 'exit' to stop." << std::endl;
}
}
return 0;
}
// Memory space savior :
#include <iostream>
#include <tdigest/TDigest.h> //this is the key https://github.com/derrickburns/tdigest/blob/master/TDigest.h
int main() {
TDigest digest;
double number;
// Read numbers from stdin until EOF
while (std::cin >> number) {
digest.add(number);
std::cout << "The estimated median of all numbers to now is: " << digest.percentile(50) << '\n';
}
return 0;
}