Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Problem Statement
2.1.
Sample Examples
3.
Approach
3.1.
Pseudocode
3.2.
Implementation
3.2.1.
Code in Java
3.2.2.
Code in C++
3.2.3.
Complexity Analysis
4.
Frequently Asked Questions
4.1.
How do you declare an Array in C++?
4.2.
What does time complexity mean?
4.3.
What does space complexity mean?
4.4.
How do you declare an array in Java?
4.5.
Which sorting is best for an array?
5.
Conclusion
Last Updated: Mar 27, 2024

Program for Mean and Median of an unsorted array

Introduction

This article will look at the problem of finding the mean and median from an unsorted array. Array-based questions are the most popular and vital in coding interviews and programming competitions. Let's understand the problem statement.

Also See, Array Implementation of QueueRabin Karp Algorithm

Problem Statement

We have given an unsorted array of sizes n, and we have to find the mean and median from the array.

Here, we will first discuss the mean calculation and then the median. By definition, the Mean of an array equals the sum of all elements divided by the number of elements. 

The Median of a sorted array is said to be the middle-most element if the size of the input array is odd and the average of the middle two elements if the size is even. If the array is not sorted, the first task is to sort the array, and then only we can apply the given logic.

Sample Examples

Example 1:

Input: 
a[] = {2, 3, 4, 1, 6, 5, 8, 7}

Output:
Mean = 4.5
Median = 4.5

Explanation: For mean: Here, the sum of all elements is 36 and the number of elements is 8, so the mean becomes 36/8= 4.5.
For median: On sorting the array it becomes, {1,2,3,4,5,6,7,8} and the number of elements here is 8 (even), so the median becomes the average of the sum of two middle-most elements which is (4+5)/2= 4.5.

 

Example 2:

Input: 
a[] = {3, 5, 2, 1, 7}

Output:
Mean: 3.6
Median: 3

Explanation: For mean: Here, the sum of all elements is 18 and the number of elements is 5, so the mean becomes 18/5= 3.6.
For median: On sorting the array it becomes, {1,2,3,5,7} and the number of elements here is 5 (odd), so the median becomes the average of the middle elements which is 3.

Approach

We can calculate the mean and median by the formula given above i.e. using the formula for mean where we divide the sum of elements by their number. For median, we take average of the middle elements.

Pseudocode

The approach is given below:

Step 1→ Declare a function for calculating the mean
   double mean(int a[], int n)
      declare int sum = 0
      Loop For int i = 0 and i < n and i++
         Set sum += a[i]
      End
      return (double)sum/(double)size
      
Step 2→ declare function for calculating median
   double median(int a[], int n)
      call sort(a, a+n)
      IF (n % 2 != 0)
         return (double)a[n/2]
      End
      return (double)(a[(n-1)/2] + a[n/2])/2.0
      
Step 3→ In main()
   Declare int a[] = {3,5,2,1,7,8}
   Declare int n = sizeof(arr)/sizeof(arr[0])
   Call mean(a, n)
   Call median(a, n)

Implementation

Code in Java

// Java program to find mean and median of an unsorted array
import java.util.*;
Class CN
{
// Function for calculating mean
   public static double Mean(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 Median(int a[], int n)     
   {
   // First we sort the array
       Arrays.sort(a);
       if (n % 2 != 0)
           return (double)a[n / 2];        //for even
       return (double)(a[(n - 1) / 2] + a[n / 2]) / 2.0; //for odd
   }
// Driver code
   public static void main(String args[])
   {
       int a[] = { 2, 3, 4, 1, 7, 5, 8, 6 };
       int n = a.length;
   // Function call
       System.out.println("Mean: " + Mean(a, n));
       System.out.println("Median: " + Median(a, n));
   }
}
You can also try this code with Online Java Compiler
Run Code

 

Output:

Mean: 4.5
Median: 4.5
You can also try this code with Online C++ Compiler
Run Code

 

Code in C++

// C++ program to find mean and median of an unsorted array
#include <bits/stdc++.h>
using namespace std;


// Function for calculating mean
double mean(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 median(int a[], int n){
  sort(a, a+n);
  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[] = {3,5,2,1,7,8};
  int n = sizeof(a)/sizeof(a[0]);
  cout << "Mean: " << mean(a, n)<<endl;
  cout << "Median: " << median(a, n) << endl;
  return 0;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Mean: 4.33333
Median: 4
You can also try this code with Online C++ Compiler
Run Code

Complexity Analysis

Time complexity:

Time Complexity to find mean is O(n).

Time Complexity to find median is O(N log N) as we need to sort the array first.

 

Space complexity:

Space Complexity is O(1) as no extra space is used.

Frequently Asked Questions

How do you declare an Array in C++?

An array is fixed in length i.e static in nature. Array declaration syntax in C/C++:

DataType ArrayName [size];

What does time complexity mean?

The time complexity in computer science is the computational complexity that describes how long it takes a computer to run an algorithm. Choosing the most efficient algorithm is always better when a fundamental problem can be solved using multiple methods.

What does space complexity mean?

The space complexity of an algorithm is the total space taken by the algorithm with respect to the input size. In simple words, An algorithm's amount of memory is known as its space complexity.

How do you declare an array in Java?

We declare an array in Java by giving a type and name: int[] ArrayName; To initialize an array as we declare it, meaning we assign values when we create the array, we can utilize the following shorthand syntax: int[] ArrayName = {5, 8, 9};

Which sorting is best for an array?

The quicksort algorithm is better if the size of the input is vast. But, insertion sort is more efficient than quicksort if the array is of small size as the number of swaps and comparisons are less than quicksort. So we combine the two algorithms to sort efficiently using both approaches.

Conclusion

This article discussed the solution for finding the mean and median of an unsorted array with its algorithm, implementation, and code in both JAVA and C++.

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem DesignMachine learning and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the problemsinterview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass