0% found this document useful (0 votes)
11 views1 page

What Is Median of An Array

Uploaded by

Ujaan Datta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views1 page

What Is Median of An Array

Uploaded by

Ujaan Datta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

What is Median of an Array?

The median of array is the middle element of a sorted array in case of odd number of
elements in an array and average of middle two elements when the number of
elements in an array is even.

Since the array is not sorted here,we sort the array first, then apply the above formula.

Example
Input:
arr[]: {1, 5, 2, 3, 9, 12, 6}

Output:
5

Explanation:

Here, the sorted sequence of the given array of integers is 1 2 3 5 6 9 12 and the output
is 5 because there are odd number of elements in an array that is 7 and and the 4 th
element in the sorted array will be our answer, which is 5.

Approach
The approach to find the median of array is to check if the array is sorted or not, the first
task is to sort the array, then find the middle element of an sorted array in case of odd
number of elements in an array and when the number of elements in an array is even
calculate the average of middle two elements (using array indexing).

Algorithm
1. Create a function to find the median of an array that takes the array.
2. First, we will sort the given array.
3. Then check for even case i.e if (size % 2 != 0) return (double)arr[size/2];.
4. In the case of odd numbers of elements in an array return (double)(arr[(size-1)/2] +
arr[size/2])/2.0;.

Code:

You might also like