Skip to content

Commit

Permalink
Create MedianInStreamOfIntegers
Browse files Browse the repository at this point in the history
  • Loading branch information
pranitha-sridhar authored Oct 28, 2022
1 parent febae80 commit d19194b
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions C++/MedianInStreamOfIntegers
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
priority_queue<int> mxleft;
priority_queue<int,vector<int>,greater<int>> mnright;
double median=0.0;
int i=0;
vector<int> arr;
void insertHeap(int &x)
{
arr.push_back(x);
}

double getMedian()
{
if(arr.size()==1){median=arr[0];mxleft.push(median);}
else{
if(mxleft.size()==mnright.size()){
if (arr[arr.size()-1]<median)
{
mxleft.push(arr[arr.size()-1]);
median = mxleft.top();
}
else
{
mnright.push(arr[arr.size()-1]);
median = (double)mnright.top();
}
}
else if(mxleft.size()>mnright.size()){
if (arr[arr.size()-1]<median)
{
mnright.push(mxleft.top());
mxleft.pop();
mxleft.push(arr[arr.size()-1]);
}
else
mnright.push(arr[arr.size()-1]);

median=(mnright.top()+mxleft.top())/2.0;
}
else{
if(arr[arr.size()-1]<median){
mxleft.push(arr[arr.size()-1]);
}
else{
mxleft.push(mnright.top());
mnright.pop();
mnright.push(arr[arr.size()-1]);
}
median=(mnright.top()+mxleft.top())/2.0;
}
}
return median;
}

0 comments on commit d19194b

Please sign in to comment.