Mean and Median of an Array
Last Updated :
27 Jun, 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:
- The mean is calculated by summing all elements and dividing by the size of the array.
- For the median, the array is first sorted; then the middle element is taken if the size is odd, or the average of the two middle elements if the size is even.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int mean(vector<int>& arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
// we can calculate sum by using this function -> accumulate(arr.begin(),arr.end(),0);
// Floor of the mean
return sum / arr.size();
}
int median(vector<int>& arr) {
int n = arr.size();
// sorting the arrat 'arr' using built in functions
sort(arr.begin(), arr.end());
int result = 0;
// if there are two middle element
if (n % 2 == 0) {
result = (arr[n / 2] + arr[(n / 2) - 1]) / 2;
}
// if there are only one middle element
else {
result = arr[n / 2];
}
return result;
}
int main() {
vector<int> arr = {2, 3, 4, 8};
int meanValue = mean(arr);
int medianValue = median(arr);
cout << meanValue << " " << medianValue << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Comparator for qsort
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int mean(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// Floor of the mean
return sum / n;
}
int median(int arr[], int n) {
// sorting function
qsort(arr, n, sizeof(int), compare);
int result = 0;
// if there are two middle element
if (n % 2 == 0) {
result = (arr[n / 2] + arr[(n / 2) - 1]) / 2;
}
// if there are only one middle element
else {
result = arr[n / 2];
}
return result;
}
int main() {
int arr[] = {2, 3, 4, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int meanValue = mean(arr, n);
int medianValue = median(arr, n);
printf("%d %d\n", meanValue, medianValue);
return 0;
}
Java
import java.util.Arrays;
class GfG {
public static int mean(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
// Floor of the mean
return sum / arr.length;
}
public static int median(int[] arr) {
int n = arr.length;
// sorting function
Arrays.sort(arr);
int result = 0;
// if there are two middle element
if (n % 2 == 0) {
result = (arr[n / 2] + arr[(n / 2) - 1]) / 2;
}
// if there are only one middle element
else {
result = arr[n / 2];
}
return result;
}
public static void main(String[] args) {
int[] arr = {2, 3, 4, 8};
int meanValue = mean(arr);
int medianValue = median(arr);
System.out.println(meanValue + " " + medianValue);
}
}
Python
def mean(arr):
sum_val = 0
for num in arr:
sum_val += num
# we can also calculate sum by using this function -> sum(arr)
# Floor of the mean
return sum_val // len(arr)
def median(arr):
n = len(arr)
# sorting function
arr.sort()
result = 0
# if there are two middle element
if n % 2 == 0:
result = (arr[n // 2] + arr[(n // 2) - 1]) // 2
# if there are only one middle element
else:
result = arr[n // 2]
return result
def main():
arr = [2, 3, 4, 8]
meanValue = mean(arr)
medianValue = median(arr)
print(meanValue, medianValue)
if __name__ == "__main__":
main()
C#
using System;
class GfG {
public static int mean(int[] arr) {
int sum = 0;
foreach (int num in arr) {
sum += num;
}
// we can also calculate sum by using this function -> arr.Sum();
// Floor of the mean
return sum / arr.Length;
}
public static int median(int[] arr) {
int n = arr.Length;
// sorting function
Array.Sort(arr);
int result = 0;
// if there are two middle element
if (n % 2 == 0) {
result = (arr[n / 2] + arr[(n / 2) - 1]) / 2;
}
// if there are only one middle element
else {
result = arr[n / 2];
}
return result;
}
public static void Main() {
int[] arr = {2, 3, 4, 8};
int meanValue = mean(arr);
int medianValue = median(arr);
Console.WriteLine(meanValue + " " + medianValue);
}
}
JavaScript
function mean(arr) {
let sum = 0;
for (let num of arr) {
sum += num;
}
// Floor of the mean
return Math.floor(sum / arr.length);
}
function median(arr) {
let n = arr.length;
// sorting function
arr.sort((a, b) => a - b);
let result = 0;
// if there are two middle element
if (n % 2 === 0) {
result = Math.floor((arr[n / 2] + arr[(n / 2) - 1]) / 2);
}
// if there are only one middle element
else {
result = arr[Math.floor(n / 2)];
}
return result;
}
let arr = [2, 3, 4, 8];
let meanValue = mean(arr);
let medianValue = median(arr);
console.log(meanValue + " " + medianValue);
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:
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read