95.6k views
3 votes
You are given an array x of int elements along with an int variable n that contains the number of elements in the array. There are no duplicates in this array. You are also given an int variable m that has been declared. Assign to m the median value of the array. NOTE: The median of a set of numbers is the number in the set such that there are as many numbers above that value as there are below. If the set has an even number of members, the median is the average of the pair of numbers such that there are as many numbers above the pair as there are below.EXAMPLE 1: Given 5 8 1 9 7 the median is 7 because there are two numbers below (1 5) and two numbers above (8 9).

EXAMPLE 2: Given 3 7 1 4 6 9 the median is the average of 4 and 6 because there are two numbers above 4 and 6 (7 9) and two numbers below (3 1).

User ADJ
by
5.1k points

1 Answer

5 votes

Answer:

//Given variables,

int [ ] x = array of integer elements

int n = x.length // number of elements in array x

int m //not set yet

//Custom variable(s)

int [ ] sortedx = sorted form of array x

double medianpos = hold the median position

//Find if n is odd or even

if (n % 2 == 0){ //if the modulus of n by 2 gives zero(0)

n is even

medianpos = n/2

m = (sortedx [medianpos -1] + sortedx [medianpos] ) / 2

}

else{

n is odd

medianpos = (n+1) / 2 // add 1 to n and divide the result by 2

m = sortedx [medianpos - 1] // since arrays are indexed from zero(0)

}

Step-by-step explanation:

Explanations are written as comments in the answer.

Hope it helps!

User QMFNP
by
5.9k points