求向量中位数的函数?
Function to find the median of a vector?
我正在尝试编写一个函数来查找给定数组的中位数。我遇到一个问题,当它开始未排序时,它不会为偶数或奇数输出正确的值。然而,排序的输入工作。有人看到我的代码有什么问题吗?谢谢!
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);
}
这是错误的,因为它在根据 n
:
做出决定后使用 i
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;
}
我正在尝试编写一个函数来查找给定数组的中位数。我遇到一个问题,当它开始未排序时,它不会为偶数或奇数输出正确的值。然而,排序的输入工作。有人看到我的代码有什么问题吗?谢谢!
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);
}
这是错误的,因为它在根据 n
:
i
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;
}