我正在尝试编写一个找到给定数组中位数的函数。我遇到一个问题,即当未排序时,它不输出偶数或奇数的正确值。但是,已排序的输入有效。有人看到我的代码有什么问题吗?谢谢!
double vect_median( const double x[], unsigned length)
{
double ordered[LENGTH] = {0}; //new vector to hold the ordered items, use of {} to accommodate larger sizes
int temp = 0; //var to hold the value of an item for re-arrangement
float result = 0;
for (size_t k = 0; k < length; ++k)
{
ordered[k] = x[k];
}
for (size_t i = 1; i < length; ++i) //loops to order the values of the vector, start at 1 because length != 0
{
for (size_t n = 0; n < (length - 1); ++n) //loop to indivudally check each value
{
if (ordered[n] > ordered[n + 1]) //if first is greater than second
{
temp = ordered[n]; //switch the order of the two values
ordered[i] = ordered[i + 1];
ordered[i+1] = temp;
}
}
//once a value is switched, the loops breaks and the outside loop runs it again LENGTH times
if(length % 2 == 1)//if odd
{
result = ordered[LENGTH/2]; //return the val in the middle of the dataset
}
else
{
result = (ordered[LENGTH/2] + ordered[LENGTH/2 - 1])/2;
}
}
return(result);
}
这是错误的,因为它基于i
做出决定后使用了n
:
if (ordered[n] > ordered[n + 1]) //if first is greater than second
{
temp = ordered[n]; //switch the order of the two values
ordered[i] = ordered[i + 1];
ordered[i+1] = temp;
}