1.使用algorithm,最大堆最小堆 vector
左边最大堆,右边最小堆,
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
class DynamicArray
{
public:
void Insert(T num)
{
if(((max.size()+min.size())&1)==0)
{
if(max.size()>0 && num<max[0])
{
max.push_back(num);
push_heap(max.begin(),max.end(),less<T>());
num = max[0];
pop_heap(max.begin(),max.end(),less<T>());
max.pop_back();
}
min.push_back(num);
push_heap(min.begin(),min.end(),greater<T>());
}
else
{
if(min.size()>0 && min[0]<num)
{
min.push_back(num);
push_heap(min.begin(),min.end(),greater<T>());
num = min[0];
pop_heap(min.begin(),min.end(),greater<T>());
min.pop_back();
}
max.push_back(num);
push_heap(max.begin(),max.end(),less<T>());
}
}
T GetMedian()
{
int size = max.size()+min.size();
if(size == 0)
throw exception("no numbers are available");
if((size&1)==1)
return min[0];
else
return (min[0]+max[0])/2;
}
private:
vector<T> max;
vector<T> min;
};
void Test(char* testName, DynamicArray<double>& numbers, double expected)
{
if(testName != NULL)
printf("%s begins: ", testName);
if(abs(numbers.GetMedian() - expected) < 0.0000001)
printf("Passed.\n");
else
printf("FAILED.\n");
}
int main(int argc, char* argv[])
{
DynamicArray<double> numbers;
printf("Test1 begins: ");
try
{
numbers.GetMedian();
printf("FAILED.\n");
}
catch(exception e)
{
printf("Passed.\n");
}
numbers.Insert(5) ;
Test("Test2", numbers, 5); //5
numbers.Insert(2);
Test("Test3", numbers, 3.5); //2 5
numbers.Insert(3);
Test("Test4", numbers, 3); //2 3 5
numbers.Insert(4);
Test("Test6", numbers, 3.5);//2 3 4 5
numbers.Insert(1);
Test("Test5", numbers, 3); //1 2 3 4 5
numbers.Insert(6);
Test("Test7", numbers, 3.5);//1 2 3 4 5 6
numbers.Insert(7);
Test("Test8", numbers, 4); // 1 2 3 4 4 5 6
numbers.Insert(0);
Test("Test9", numbers, 3.5);// 0 1 2 3 4 4 5 6
numbers.Insert(8);
Test("Test10", numbers, 4);// 0 1 2 3 4 4 5 6 8
return 0;
}