#include
#include
#include
using namespace std;
void insert_no(priority_queue &first_queue,priority_queue<double,vector,greater> &second_queue,int n)
{
///first_queue is Max_Queue
///second_queue is Min_Queue
{
if(first_queue.empty()||(n<first_queue.top()))
first_queue.push(n);
else ///if(second_queue.empty()||(n>second_queue.top()))
second_queue.push(n);
if(first_queue.size()==second_queue.size()+2)
{
second_queue.push(first_queue.top());
first_queue.pop();
}
else if(second_queue.size()==first_queue.size()+2)
{
first_queue.push(second_queue.top());
second_queue.pop();
}
}
}
double median(priority_queue &first_queue,priority_queue<double,vector,greater> &second_queue)
{
if(first_queue.size()==second_queue.size())
return (first_queue.size()==0?0:(first_queue.top()+second_queue.top()/2.0));
else if(first_queue.size()==second_queue.size()+1)
return first_queue.top();
else /// (first_queue.size()+1==second_queue.size())
return second_queue.top();
}
int main ()
{
int n;
cin>>n;
priority_queuefirst_queue;
priority_queue<double,vector,greater>second_queue;
while(n!=-1)
{
insert_no(first_queue,second_queue,n);
cin>>n;
}
cout<<median(first_queue,second_queue);
}
I’m not getting the output correctly when I give the input
Input-9 3 5 4 7 -1
Output-6.5
But the output should have been 4.5