Skip to content

Instantly share code, notes, and snippets.

@sashang
Created August 24, 2016 14:52
Show Gist options
  • Save sashang/243babf54c76c2624d118fe48f35890b to your computer and use it in GitHub Desktop.
Save sashang/243babf54c76c2624d118fe48f35890b to your computer and use it in GitHub Desktop.
median tracking
if (min_heap.size() == max_heap.size())
{
if (u < max_heap.top())
{
max_heap.push(u);
total += max_heap.top();
}
else
{
min_heap.push(u);
total += min_heap.top();
}
}
else if (min_heap.size() < max_heap.size())
{
if (u < max_heap.top())
{
max_heap.push(u);
int temp = max_heap.top();
max_heap.pop();
min_heap.push(temp);
assert(min_heap.size() == max_heap.size());
}
else
{
min_heap.push(u);
assert(min_heap.size() == max_heap.size());
}
total += max_heap.top();
}
else //min_heap has more elements
{
if (u < max_heap.top())
{
max_heap.push(u);
assert(min_heap.size() == max_heap.size());
}
else
{
min_heap.push(u);
int temp = min_heap.top();
min_heap.pop();
max_heap.push(temp);
assert(min_heap.size() == max_heap.size());
}
total += max_heap.top();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment