how to find the median in c++

from smallest to largest this is what I have

if(grades[0] < grades[1] && grades[0] < grades[2] && grades[0] < grades[3] && grades[0] < grades[4])
{
cout<<grades[0]<<" "<<grades[1]<<" "<<grades[2]<<" "<<grades[3]<<" "<<grades[4]<<endl;
med_grade = grades[2];
}
else if(grades[1] < grades[0] && grades[1] < grades[2] && grades[1] < grades[3] && grades[1] < grades[4])
{
cout<<grades[1]<<" "<<grades[0]<<" "<<grades[2]<<" "<<grades[3]<<" "<<grades[4]<<endl;
med_grade = grades[2];
}
else if(grades[2] < grades[1] && grades[2] < grades[0] && grades[2] < grades[3]&& grades[2] < grades[4])
{
cout<<grades[2]<<" "<<grades[1]<<" "<<grades[0]<<" "<<grades[3]<<" "<<grades[4]<<endl;
med_grade = grades[0];
}
else if(grades[3] < grades[2] && grades[3] < grades[0] && grades[3] < grades[1] && grades[3] < grades[4]) https://www.indigocard.org/
{
cout<<grades[3]<<" "<<grades[2]<<" "<<grades[0]<<" "<<grades[1]<<" "<<grades[4]<<endl;
med_grade = grades[0];
}
else if(grades[4] < grades[3] && grades[4] < grades[0] && grades[4] < grades[1] && grades[4] < grades[2])
{
cout<<grades[4]<<" "<<grades[3]<<" "<<grades[0]<<" "<<grades[1]<<" "<<grades[2]<<endl;
med_grade = grades[0];
}

I know that there better ways to find the median. is there a sort function in C++. another idea i had was to use the sort function, and what ever number was in [2] would be the median.
Last edited on
C++ has many toys to play with.
https://en.cppreference.com/w/cpp/algorithm/sort
salem c wrote:
C++ has many toys to play with.

Also,
std::partial_sort
and
std::nth_element
can be used for the purposes of finding the median.
Last edited on
Topic archived. No new replies allowed.