Write a program to read a list of n integers and find their
median.
Note: The median value of a list of values is the middle one
when they are arranged in order. If there are two middle values
then take their average.
Hint: Use an inbuilt function to sort the list
Answers
Explanation:
Median of a sorted array of size n is defined as the middle element when n is odd and average of middle two elements when n is even.
Since the array is not sorted here, we sort the array first, then apply above formula.
Examples:
Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output : Mean = 4.5
Median = 4.5
Sum of the elements is 1 + 3 + 4 + 2 + 6 +
5 + 8 + 7 = 36
Mean = 36/8 = 4.5
Since number of elements are even, median
is average of 4th and 5th largest elements.
which means (4 + 5)/2 = 4.5
Input : a[] = {4, 4, 4, 4, 4}
Output : Mean = 4
Median = 4
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Below is the code implementation:
C++
// CPP program to find mean and median of
// an array
#include <bits/stdc++.h>
using namespace std;
// Function for calculating mean
double findMean(int a[], int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
sum += a[i];
return (double)sum/(double)n;
}
// Function for calculating median
double findMedian(int a[], int n)
{
// First we sort the array
sort(a, a+n);
// check for even case
if (n % 2 != 0)
return (double)a[n/2];
return (double)(a[(n-1)/2] + a[n/2])/2.0;
}
// Driver program
int main()
{
int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 };
int n = sizeof(a)/sizeof(a[0]);
cout << "Mean = " << findMean(a, n) << endl;
cout << "Median = " << findMedian(a, n) << endl;
return 0;
}
The following codes are written in Python.
Source code:
n = int(input("Enter the number of integers you'd like to enter: "))
l = list()
for i in range(n):
x = int(input("Enter the integer: "))
l.append(x)
print(l, "is your given list.")
l.sort()
print(l, "is the sorted list.")
c = len(l)
if c%2 != 0:
med = c//2
print(l[med], "is the median.")
else:
a = l[c//2]
b = l[(c//2) - 1]
s = a + b
med = s/2
print(med, "is the median.")