C Exercises: Find the median of the elements in a queue
13. Queue Median Calculation
Write a C program to find the median of the elements in a queue.
From Wikipedia,
In statistics and probability theory, the median is the value separating the higher half from the lower half of a data sample, a population, or a probability distribution.
The median of a finite list of numbers is the "middle" number, when those numbers are listed in order from smallest to greatest.
If the data set has an odd number of observations, the middle one is selected. For example, the following list of seven numbers,
1, 3, 3, 6, 7, 8, 9
has the median of 6, which is the fourth value.
If the data set has an even number of observations, there is no distinct middle value and the median is usually defined to be the arithmetic mean of the two middle values. For example, this data set of 8 numbers1, 2, 3, 4, 5, 6, 8, 9 has a median value of 4.5, that is (4+5)/2 . (In more technical terms, this interprets the median as the fully trimmed mid-range).
Sample Solution:
C Code:
Output:
Input some elements into a queue: Queue elements are: 1 2 3 4 5 The median of the elements in the queue is 3.000000 Input one more element: Queue elements are: 1 2 3 4 5 6 The median of the elements in the queue is 3.500000
Flowchart
For more Practice: Solve these Related Problems:
- Write a C program to dynamically calculate the median of a queue as elements are enqueued and dequeued.
- Write a C program to compute the median of a linked list queue using a two-pointer technique.
- Write a C program to find the median in a circular queue after each dequeue operation with minimal recomputation.
- Write a C program to maintain a sorted auxiliary structure for a queue to retrieve the median in constant time.
C Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Sort a queue in ascending order.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.