I am writing a routine to calculate median using the minimum of the numbers and then changing the value of the minimum to a large value outside the range of numbers (assuming you know the nature of the numbers). I know I could use many other proven techniques, but have chosen to play around with this one.
I don't see why the performance is poor. There are 3 loops, however only two are nested at any one time. There is no sorting involved, only finding the first occurrence of a minimum and making the new value outside the range. If it finds the same number a second time, it ignores the number until the next iteration. It iterates for half of the total series before the median is found. It works dandy except for the speed.
How do I improve the efficiency of this code?
float trashMin(float array[], unsigned int length, float median){
//what we want to do in this routine is find the lowest in the array
//we then make the lowest number, the same as the highest possible number and
//after iteratively going through the array 1/2 of the full length we will find the median
unsigned int halflength = (length / 2) + 1;
unsigned int i = 0;
unsigned int j = 0;
unsigned int k = 0;
float highNumber = 999.0;//this is an arbitrary number, well outside of range of the number series
float median = 0;
for (i = 0; i < halflength; ++i)
{
float lowestInArray = array[0];
bool firstTime = true;// is it the first time we see this number
for (j = 0; j < length; ++j)
{// find the lowest and highest number in the array
float comparitor = array[j];
lowestInArray = (lowestInArray < comparitor) ? lowestInArray : comparitor;
}//end j
// now that we know which is the smallest number, eliminate only 1st occurance of it
for (k = 0; k < length; ++k)
{
float comparitor = array[k];
if (comparitor == lowestInArray && firstTime == true)
{
array[k] = highNumber;
firstTime = false;
}
}//end k
median = lowestInArray;
}//end i
return median;
}