Open In App

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

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Find the size of the list using the list::size() function.
  • Declare an iterator at the beginning of the list.
  • If the size of the list is odd then the median is the element at the middle index.
    • Use the std::advance method to move the iterator to the size/2 position in the list.
  • If the size of the list is even then the median will be the average of the two middle elements.
    • Use the std::advance method to move the iterator to size/2 -1 th position in the list and calculate the median by finding the average of the current element and the next element with the help of the iterator.

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++
// 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)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads