-
Median
Shouldn't the following code return the Median of the "Data" array?
Code:
int Median(int Data[], int Length)
{
int i = 0, j = 0, Temp = 0;
for(i; i < Length; i++)
{
for(j = 0; j < (Length - 1); j++)
{
if(Data[j] > Data[j+1])
{
Temp = Data[j+1];
Data[j+1] = Data[j];
Data[j] = Temp;
}
}
}
i = (Length / 2);
if((Length % 2) == true)
{
return(Data[i]);
}
else
{
if(Data[i] == Data[i+1])
{
return(Data[i]);
}
else
{
return((Data[i] + Data[i-1]) / 2);
}
}
}
If the Data array contains 4 - 4 - 5 - 6 -6 the function returns 4 as the median, rather than 5, why is that? What have i done wrong?
-
It returned 5 when I ran it. Maybe your main() is different.
-
yeah check ur main(). im getting 5 as well. it should look something like this:
Code:
int main(){
int data[5] = {4,4,5,6,6};
cout << Median(data, 5) << endl;
return 0;
}
-
I just realized.
I was reading the data into the array from a file, with a number on each line. The last line in the file was empty though, so i guess the length of the file got screwed up, and the length passed to the function was wrong. Stupid mistake, sorry about that.
-
Make sure you aren't using eof() to control your loop, as that can screw those things up as well.