VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-find-median-of-all-elements-in-a-deque-in-cpp/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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++.


Output
Median = 4.5

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



Comment