Monday, February 18, 2013

find median


#include<iostream>
#include<queue>

using namespace std;

int Selection_Algorithm(vector<int> input_array,int k)
{
int size=input_array.size();
int pos=rand()%size;
swap(input_array[size-1],input_array[pos]);
int x=input_array[size-1];
int i=-1;
for(int j=0;j<=size-2;j++)
{
if(input_array[j]<=x)
{
i=i+1;
swap(input_array[i],input_array[j]);
}
}
swap(input_array[i+1],input_array[size-1]);
if(i+1==k)
return input_array[i+1];
else if(i+1<k)
{
vector<int> sub_array(input_array.begin()+(i+2),input_array.end());
return Selection_Algorithm(sub_array,k-i-2);
}
else if(i+1>k)
{
vector<int> sub_array(input_array.begin(),input_array.begin()+i);
return Selection_Algorithm(sub_array,k);
}

}


void Find_median(vector<int> input_array)
{
priority_queue<int,vector<int>,less_equal<int>> queue1;
priority_queue<int,vector<int>,greater_equal<int>> queue2;
int size=input_array.size();
for(int i=0;i<size;i++)
{
int size1=queue1.size(),size2=queue2.size();
if(size1==0 || input_array[i]<queue1.top())
queue1.push(input_array[i]);
else if(size2==0 || input_array[i]>queue2.top())
queue2.push(input_array[i]);
if(size1>size2+1)
{
int max_elem=queue1.top();
queue1.pop();
queue2.push(max_elem);
}
else if(size1<size2-1)
{
int min_elem=queue2.top();
queue2.pop();
queue1.push(min_elem);
}
}
if(queue1.size()<queue2.size())
cout<<queue2.top()<<endl;
else
cout<<queue1.top()<<endl;

}

No comments:

Post a Comment