Skip to content
Related Articles
Open in App
Not now

Related Articles

Program for Mean and median of an unsorted array

Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 31 Mar, 2023
Improve Article
Save Article
Like Article

Given an unsorted array a[] of size N, the task is to find its mean and median. 

Mean of an array = (sum of all elements) / (number of elements)

The 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
Explanation: 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 Median = (4 + 5)/2 = 4.5

Input: a[] = {4, 4, 4, 4, 4}
Output: Mean = 4, Median = 4 

Approach:  To solve the problem follow the below steps:

To find median:

  • First, simply sort the array
  • Then, check if the number of elements present in the array is even or odd
  • If odd, then simply return the mid value of the array
  • Else, the median is the average of the two middle values

To find Mean:

  • At first, find the sum of all the numbers present in the array.
  • Then, simply divide the resulted sum by the size of the array

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 code
int 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




// Java program to find mean
// and median of an array
import 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




# 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 code
a = [1, 3, 4, 2, 7, 5, 8, 6]
n = len(a)
 
# Function call
print("Mean =", findMean(a, n))
print("Median =", findMedian(a, n))
 
# This code is contributed by Smitha Dinesh Semwal


C#




// C# program to find mean
// and median of an array
using 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
// PHP program to find mean
// and median of an array
 
// Function for calculating mean
function findMean(&$a, $n)
{
    $sum = 0;
    for ($i = 0; $i < $n; $i++)
        $sum += $a[$i];
     
    return (double)$sum /
           (double)$n;
}
 
// Function for
// calculating median
function 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 call
echo "Mean = " .
      findMean($a, $n)."\n";
echo "Median = " .
      findMedian($a, $n);
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// Javascript program to find mean
// and median of an array
 
// Function for
// calculating mean
function findMean(a,n)
{
    let sum = 0;
    for (let i = 0; i < n; i++)
        sum += a[i];
 
    return sum / n;
}
 
// Function for
// calculating median
function 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 call
document.write("Mean = " + findMean(a, n) + "<br>");
document.write("Median = " + findMedian(a, n));
 
 
</script>


Output

Mean = 4.5
Median = 4.5

Complexity Analysis:

Time Complexity to find mean: O(N) 
Time Complexity to find median: O(N Log N) as we need to sort the array first. 
Auxiliary Space: O(1)

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.

Approach 2:-Using STL library

  • Declare the vector to store the elements of the unsorted array:
  • Calculate the sum of all elements in the array using the std::accumulate function:
  • Calculate the mean by dividing the sum by the number of elements in the array:
  • Sort the vector using the std::sort function to find the median:
  • Calculate the median by checking if the number of elements in the array is odd or even, and then taking the middle element(s) accordingly:

C++




#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
 
using namespace std;
 
double mean(vector<int> arr)
{
    int sum = accumulate(arr.begin(), arr.end(), 0);
    return (double)sum / arr.size();
}
 
double median(vector<int> arr)
{
    int n = arr.size();
    sort(arr.begin(), arr.end());
    if (n % 2 == 0) {
        return (double)(arr[n/2 - 1] + arr[n/2]) / 2;
    } else {
        return (double)arr[n/2];
    }
}
 
int main()
{
    vector<int> arr = { 1, 3, 4, 2, 7, 5, 8, 6 };
    cout << "Mean: " << mean(arr) << endl;
    cout << "Median: " << median(arr) << endl;
    return 0;
}


Python3




from typing import List
 
def mean(arr: List[int]) -> float:
    sum_ = sum(arr)
    return sum_ / len(arr)
 
def median(arr: List[int]) -> float:
    n = len(arr)
    arr.sort()
    if n % 2 == 0:
        return (arr[n//2 - 1] + arr[n//2]) / 2
    else:
        return arr[n//2]
 
if __name__ == '__main__':
    arr = [1, 3, 4, 2, 7, 5, 8, 6]
    print("Mean:", mean(arr))
    print("Median:", median(arr))


Java




import java.util.ArrayList;
import java.util.Collections;
 
public class Main {
    // Calculates the mean of an ArrayList of integers
    public static double mean(ArrayList<Integer> arr) {
        int sum = 0;
        // Iterate over the ArrayList and add it to the sum
        for (int i : arr) {
            sum += i;
        }
        // Divide the sum by the number of elements to get the mean
        return (double) sum / arr.size();
    }
 
    // Calculates the median of an ArrayList of integers
    public static double median(ArrayList<Integer> arr) {
        int n = arr.size();
        // Sort the ArrayList in ascending order
        Collections.sort(arr);
        if (n % 2 == 0) {
            // If even number of elements, calculate the average of the two middle elements
            return (double) (arr.get(n / 2 - 1) + arr.get(n / 2)) / 2;
        } else {
            // If odd number of elements, return the middle element
            return (double) arr.get(n / 2);
        }
    }
 
    public static void main(String[] args) {
        // Create an ArrayList of integers and add some values
        ArrayList<Integer> arr = new ArrayList<Integer>();
        arr.add(1);
        arr.add(3);
        arr.add(4);
        arr.add(2);
        arr.add(7);
        arr.add(5);
        arr.add(8);
        arr.add(6);
 
        // Print the mean and median of the ArrayList
        System.out.println("Mean: " + mean(arr));
        System.out.println("Median: " + median(arr));
    }
}


Output

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. 

The time complexity of this program is O(n log n) due to the use of the std::sort function, which has an average-case time complexity of O(n log n). The std::accumulate function used to calculate the sum of elements has a time complexity of O(n).

Auxiliary Space: O(N)

The time complexity of this program is O(n log n) due to the use of the std::sort function, which has an average-case time complexity of O(n log n). The std::accumulate function used to calculate the sum of elements has a time complexity of O(n).


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!