Program for Mean and median of an unsorted array - GeeksforGeeks

23 Aug, 2021
Given n size unsorted array, find it’s mean and median. 
Mean of an array = (sum of all elements) / (number of elements)
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 
Below is the code implementation: 
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find mean and median of// an array#include <bits/stdc++.h>using namespace std; // Function for calculating meandouble 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 mediandouble 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 codeint main(){    int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 };    int n = sizeof(a) / sizeof(a[0]);       // Function call    cout << "Mean = " << findMean(a, n) << endl;    cout << "Median = " << findMedian(a, n) << endl;    return 0;}
// Java program to find mean// and median of an arrayimport java.util.*; class GFG{    // Function for calculating mean    public static 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    public static double findMedian(int a[], int n)    {        // First we sort the array        Arrays.sort(a);         // 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 code    public static void main(String args[])    {        int a[] = { 1, 3, 4, 2, 7, 5, 8, 6 };        int n = a.length;               // Function call        System.out.println("Mean = " + findMean(a, n));        System.out.println("Median = " + findMedian(a, n));    }} // This article is contributed by Anshika Goyal.
# Python3 program to find mean# and median of an array # Function for calculating mean  def findMean(a, n):     sum = 0    for i in range(0, n):        sum += a[i]     return float(sum/n) # Function for calculating median  def findMedian(a, n):     # First we sort the array    sorted(a)     # check for even case    if n % 2 != 0:        return float(a[int(n/2)])     return float((a[int((n-1)/2)] +                  a[int(n/2)])/2.0)  # Driver codea = [1, 3, 4, 2, 7, 5, 8, 6]n = len(a) # Function callprint("Mean =", findMean(a, n))print("Median =", findMedian(a, n)) # This code is contributed by Smitha Dinesh Semwal
// C# program to find mean// and median of an arrayusing System; class GFG{    // Function for    // calculating mean    public static 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    public static double findMedian(int[] a, int n)    {        // First we sort        // the array        Array.Sort(a);         // 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 Code    public static void Main()    {        int[] a = { 1, 3, 4, 2, 7, 5, 8, 6 };        int n = a.Length;               // Function call        Console.Write("Mean = " + findMean(a, n) + "\n");        Console.Write("Median = " + findMedian(a, n)                      + "\n");    }} // This code is contributed by Smitha .
<?php// PHP program to find mean// and median of an array // Function for calculating meanfunction findMean(&$a, $n){    $sum = 0;    for ($i = 0; $i < $n; $i++)        $sum += $a[$i];         return (double)$sum /           (double)$n;} // Function for// calculating medianfunction findMedian(&$a, $n){    // First we sort the array    sort($a);     // 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 Code$a = array(1, 3, 4, 2,           7, 5, 8, 6);$n = sizeof($a); // Function callecho "Mean = " .      findMean($a, $n)."\n";echo "Median = " .      findMedian($a, $n); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to find mean// and median of an array // Function for// calculating meanfunction findMean(a,n){    let sum = 0;    for (let i = 0; i < n; i++)        sum += a[i];     return sum / n;} // Function for// calculating medianfunction findMedian(a,n){    // First we sort    // the array    a.sort();     // check for    // even case    if (n % 2 != 0)        return a[n / 2];     return (a[Math.floor((n-1)/2)] +            a[n / 2]) / 2;} // Driver Code let a = [1, 3, 4, 2, 7, 5, 8, 6]let n = a.length; // Function calldocument.write("Mean = " + findMean(a, n) + "<br>");document.write("Median = " + findMedian(a, n));  </script>
Mean = 4.5
Median = 4.5
Time Complexity to find mean = O(n) Time Complexity to find median = O(n Log n) as we need to sort the array first. Note that we can find median in O(n) time using methods discussed here and here.
This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Smitha Dinesh Semwal
ukasp
semank
mohit kumar 29
sweetyty
maths-mean
median-finding
Order-Statistics
statistical-algorithms
Arrays
School Programming
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Python Dictionary
Inheritance in C++
Reverse a string in Java
Interfaces in Java
C++ Classes and Objects