You're probably better off using the sort function but if for some reason it doesn't work you can always use my method. |
std::list::sort suggested by cire works. There is no question about that. Just like many std functions, it's a pre-written function that's already been debugged and freely available for you to use and, by all means, take advantage of it. Of course, if you want to learn the sorting algorithm, then feel free to create your own function for sorting and that's perfectly fine as well.
I'm looking at ragecraze's first post and it looks like he already figured out how to sort the list (unless he edited his code after cire's post). Look at line 44 ...
mylist.sort(); // sorting the list from smallest to biggest number
So, I guess his question now is what to do after sorting.
Here are the steps for finding a median
1. Put all the values in numerical order. (Done)
2. If there is an odd number of results, the median is the middle number.
3. If there is an even number of results, the median will be the mean of the two central numbers.
Algorithm for finding median depends on whether n is odd or even (Here, n is the total number of values in the list). Personally, I think vector is better suited for finding a median. You should know that while inserting and removing element with std::list is constant time, it has a linear access time. Finding the median involves finding the nth element in a container and std::vector does a much better job of it than std::list.
Because you are using std::list, you have to start from begin() or end() and traverse each element until you reach the middle element.
So, for std::list, you can do the following. I wonder if there is a better way to get nth element in std::list?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// Median is double type because for even n, median is the average of 2 central values
double median;
auto itr = mylist.begin();
// n is even
if( mylist.size() % 2 == 0 ) {
for( int i = 0 ; i < mylist.size() / 2 ; i ++ ) {
itr++;
}
median = ( (double)*itr + *--itr ) / 2;
}
// n is odd
else {
for( int i = 0 ; i < mylist.size() / 2 ; i ++ ) {
itr++;
}
median = *itr;
}
|