Open In App

How to Find the Median of All Elements in a List in C++?

In C++, a list is a container that allows us to store data in non-contiguous memory locations. The median of a list is defined as the middle element when the list size is odd, and the average of the two middle elements when the list size is even. In this article, we will learn how to find the median of all elements in a list in C++.

Example:

Input: 
myList = {10, 20, 30, 40, 50, 60};

Output:
Median of the list is: 35

Finding Median of Elements Stored in a List

To compute the median of all elements in a std::list, first sort the list using the std::sort() function and then find the median using the below approach:

Approach

Note: We cannot directly access values at any position in the list using index like other containers, so we have to use std::advance function to get hold of the middle elements from the list.

C++ Program to Find the Median of All Elements in a List

The following program demonstrates how we can find the median of all elements in a std::list in C++.

// C++ program to find the median of all elements in a list

#include <algorithm>
#include <iostream>
#include <list>

using namespace std;

int main()
{
    // Creating a list of integers
    list<int> nums = { 10, 20, 30, 40, 50, 60 };

    // Sorting the list
    nums.sort();

    // Finding the median
    auto it = nums.begin();
    int n = nums.size();

    if (n % 2 == 0) {
        // Even-sized list
        advance(it, (n / 2) - 1);
        double median = (*it + *(++it)) / 2.0;
        cout << "Median of the list is : " << median
             << endl;
    }
    else {
        // Odd-sized list
        advance(it, n / 2);
        double median = *it;
        cout << "Median of the list is : " << median
             << endl;
    }

    return 0;
}

Output
Median of the list is : 35

Time Complexity: O(NlogN), where N is the number of elements in the list.
Auxiliary Space: O(1)

Article Tags :