Функция найти медиану вектора? - PullRequest
0 голосов
/ 10 марта 2020

Я пытаюсь написать функцию, которая находит медиану данного массива. У меня возникла проблема, когда он не выводит правильные значения для четного или нечетного, когда его не отсортировали для начала. Однако сортированные входы работают. Кто-нибудь видит, что не так с моим кодом? Спасибо!

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);
}

1 Ответ

1 голос
/ 10 марта 2020

Это неправильно, потому что он использует 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;

            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...