VOOZH about

URL: https://www.geeksforgeeks.org/dsa/mean-and-median-of-an-unsorted-array/

⇱ Mean and Median of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mean and Median of an Array

Last Updated : 22 Jul, 2025

Given an array arr[] of positive integers, find the Mean and Median, and return the floor of both values.

Note: Mean is the average of all elements in the array and Median is the middle value when the array is sorted, if the number of elements is even, it's the average of the two middle values.

Examples:

Input: arr[] = [1, 2, 19, 28, 5]
Output: 11 5
Explanation: Sorted array - [1, 2, 5, 19, 28], Mean = (1 + 2 + 19 + 28 + 5) / 5 = 55 / 5 = 11, Median = Middle element = 5

Input: arr[] = [2, 8, 3, 4]
Output: 4 3
Explanation: Sorted array - [2, 3, 4, 8], Mean = (2 + 3 + 4 + 8) / 4 = 17 / 4 = 4.25, so floor(4.25) is 4, Median = (3 + 4)/2 = 3.5, so floor(3.5) is 3

[Approach] Using Definition of Mean and Median

Mean (Average) : The mean is calculated by adding all elements of the array and dividing the sum by the total number of elements.
Formula: Mean = (a0 + a1 + a2 + --- + an-1) / n

Median: The median represents the middle value in a sorted array.

Steps to find the median:

  • Sort the array in non-decreasing order.
  • If the number of elements is:
    => Odd: Median = value at the middle index, Median = an/2th element
    => Even: Median = average of the two middle elements, Median = (an/2-1 + an/2) / 2.

Output
4 3

Time Complexity: O(n*log(n)), O(n) for summing all the elements, O(n*log(n)) for sorting the array.
Auxiliary Space: O(1), as no extra space is used.

We can use Library Methods for calculating sum:

Comment