![]() |
VOOZH | about |
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
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.
The below program demonstrates how we can find the median of all elements in a deque in C++.
Median = 4.5
Time Complexity: O(N log N), where N is the number of elements in the deque.
Auxiliary Space: O(logN)