I am trying to find median of constant size array. But array is always uptading. I mean new numbers are replaced with old numbers. I call this process running median, or we can say on the fly median.. Here is my code and inside the code, when rand() function generates 78, the code cannot find the correct median. (Before 78; 41, 67, 34, 0, 69, 24 was generated)
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#define MAX_SIZE 5
using namespace std;
bool isOdd( int integer )
{
if ( integer % 2 == 0 )
return false;
else
return true;
}
int main()
{
int median;
int *minArray ;
int *maxArray ;
int myArray[MAX_SIZE];
for(int i=0; i<20; i++)
{
int v = rand() %100;
cout << v << endl;
myArray[i%MAX_SIZE] = v;
if(i==0)
{
median = v;
}
else if (v>median)
{
maxArray= new int [MAX_SIZE+1];
int n;
for(n=0; n<(MAX_SIZE+1); n++)
{
if ((median<myArray[n])&&(myArray[n]<=v))
{
maxArray[n] = myArray[n];
//cout<<"asda"<<maxArray[n]<<endl;
}
else
{
maxArray[n] = 200;
//cout<<"asda"<<maxArray[n]<<endl;
}
}
if(isOdd(i)&&(i<MAX_SIZE))
median = (median+(*min_element(maxArray,maxArray+MAX_SIZE+1)))/2;
else median = (*min_element(maxArray,maxArray+MAX_SIZE+1));
//cout << ((*min_element(maxArray,maxArray+MAX_SIZE+1))) << endl;
delete [] maxArray;
}
else if (v<median)
{
minArray= new int [MAX_SIZE+1];
int n;
for(n=0; n<(MAX_SIZE+1); n++)
{
if ((median>myArray[n])&&(myArray[n]>=v))
{
minArray[n] = myArray[n];
//cout<<"asda"<<minArray[n]<<endl;
}
else
{
minArray[n] = 0;
//cout<<"asda"<<minArray[n]<<endl;
}
}
if(isOdd(i)&&(i<MAX_SIZE))
median = (median+(*max_element(minArray,minArray+MAX_SIZE+1)))/2;
else median = (*max_element(minArray,minArray+MAX_SIZE+1));
delete [] minArray;
}
cout << "median: "<< median<<endl;
}
return 0;
}
If I made some mistakes about explaning my problem, excuse me cus I am so new here.