Open In App

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

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the median of the deque is defined as the middle element when the size of the deque is odd and the average of the middle two elements when the size is even in the sorted deque. In this article, we will learn how to find the median of all elements in a deque in C++.

Example:

Input:
Deque = {3, 1, 2, 4, 5}

Output:
Median of Deque is: 3

Finding the Median of All Elements in a Deque in C++

To compute the median of all elements in a std::deque, first sort the queue using std::sort. If the number of elements in a deque is odd then the middle element is the median, otherwise for an even number of elements the average of two middle elements is a median.

Approach

  • Sort the deque elements using the std::sort function.
  • Find the size of the deque using the deque::size() function.
  • If the size of the deque is odd then the median is the element at the middle index.
  • If the size of the deque is even then the median will be the average of the two middle elements.

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

The below program demonstrates how we can find the median of all elements in a deque in C++.

C++
// C++ Program to calculate the median of a deque of
// integers

#include <algorithm>
#include <deque>
#include <iostream>
using namespace std;

int main()
{
    // initializing deque
    deque<int> d = { 5, 7, 4, 2, 6, 2, 8, 3 };

    // Sort the deque
    sort(d.begin(), d.end());

    // finding size of deque
    int n = d.size();

    // Check if the number of elements is odd
    double median;
    if (n % 2 != 0)
        median = (double)d[n / 2];
    else
        // If the number of elements is even, return the
        // average of the two middle elements
        median = (double)(d[(n - 1) / 2] + d[n / 2]) / 2.0;

    // print the median
    cout << "Median = " << median << endl;
    return 0;
}

Output
Median = 4.5

Time Complexity: O(N log N), where N is the number of elements in the deque.
Auxiliary Space: O(logN)




Article Tags :
Practice Tags :

Similar Reads