Skip to main content
1 of 3
Ulivax
  • 117
  • 1
  • 6

Median of a Vector assignment

I've been reading Bjarne's Principles in Programming and was given some code to demonstrate the usage of vectors and how we can return specific values for certain functionality such as mean and median. However, in the chapter I noticed that the code he provided was purposely made so that it doesn't always calculate the median correctly which was correct, he had purposely made it so we had to go back and alter the code as follows:

#include "../../std_lib_facilities.h"

int main()
{
    vector<double> temps;
    for (double temp; cin >> temp;)
        temps.push_back(temp);

    sort(temps);
    cout << "Median temperature: " << temps[temps.size() / 2] << '\n';
}

However, when asked in a question format it states:

If we define the median of a sequence as “a number so that exactly as many elements come before it in the sequence as come after it,” fix the program in 4.6.3 so that it always prints out a median. Hint: A median need not be an element of a sequence.

I assumed he meant that we want equal values on both sides of our median as the previous algorithm only divides the vector size by 2 and returns, if odd the middle index + 1, therefore I'm assuming that he wanted the exact median value of the range rather than a specific element within the array? Regardless, the code I had created follows:

//Program to compute the median of a temperature vector
#include "../../std_lib_facilities.h"

int main()
{
    //Define variables and Read in values
    double median_value;
    vector<double> temps;
    for (double temp; cin >> temp;)
        temps.push_back(temp);

    //Compute Median Temperatures
    sort(temps);

    if (temps.size() % 2 == 0)
        median_value = (temps[temps.size() / 2] + temps[temps.size() / 2 - 1]) / 2;
    else 
        median_value = temps[temps.size() / 2];

    cout << "Median Temperature of input values: " << median_value << '\n';
    for (int i = 0; i < temps.size(); ++i) cout << temps[i] << ", ";
}

I'm assuming this is what he meant by “a number so that exactly as many elements come before it in the sequence as come after it". I've probably missed the point of this exercise hence the post for some verification that I completed the exercise correctly.

Ulivax
  • 117
  • 1
  • 6