C Program for Mean and Median of an Unsorted Array
In this tutorial, we will look at how to determine the mean and median of a given unsorted array.
To determine the Mean:
To get the average, mean is determined. The formula provided can be used to get the mean
Mean of a given array = summation of all the element / Total number of element
To determine the Median:
If an array is sorted, the median is the middle element when there are odd numbers of items, and when there are even numbers of elements, it is the average of two middle elements.
The array must first be sorted if it is not already sorted, and only then may the provided logic be used.
- If the total number is odd type,
For example, given numbers are 1, 2, 3, 4, 5
Median will be 3.
- If the total number is even type,
For example, given numbers are 4, 5, 7, 8
Median will be ( (5 + 7) / 2 ) = 6.
C++ Program:
// Using CPP, determine the mean and median of the given array
#include <bits/stdc++.h>
using namespace std;
// Using function to find mean
double findingMean ( int array [], int num )
{
int sum = 0;
for (int index = 0; index < num; index++)
sum += array [index];
return (double) sum / (double) num ;
}
// Using function to find median
double findingMedian ( int array [], int num )
{
// Initially we have to do array sorting
sort ( array, array + num );
// Checkinng whether it is even or not
if ( num % 2 != 0 )
return ( double ) array [ num / 2 ];
return (double) ( array [ ( num - 1 ) / 2 ] + array [ num / 2 ] ) / 2.0;
}
// Main function
int main ()
{
int array [] = { 2, 4, 5, 3, 8, 6, 9, 7 };
int num = sizeof (array) / sizeof (array [0] );
// Calling functions
cout << "Mean is: " << findingMean ( array, num ) << endl;
cout << "Median is: " << findingMedian ( array, num ) << endl;
return 0;
}
Output:
The output that will be produced if the code above is run is as follows:
Mean is: 5.5
Median is: 5.5
- Time Complexity: O (n) [For mean]
- Time Complexity: O (n Log n) [For Median]
[so we must first sort the array. Consider that approaches allow us to find the median in O (n) time.]
- Space Complexity for both: O (1)