143k views
4 votes
C++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 Jacobian
by
5.6k points

1 Answer

5 votes

Answer:

C++ Code

#include <iostream>

using namespace std;

int median(int x[], int n)

{

for (int i = 0; i < n-1; i++)

{

for (int j = 0; j < n-i-1; j++)

if (x[j] > x[j+1])

{

int temp = x[j];

x[j] = x[j+1];

x[j+1] = temp;

}

}

if( n%2 == 0 )

{

return (x[ (n/2) -1] + x[n/2])/2;

}

else

return x[n/2];

}

int main()

{

//example 1

int x[] = {5,8,1,7,9};

int n = 5;

int m = 0;

m = median(x,n);

cout << m << endl;

//example 2

int x2[] = {3,7,1,4,6,9};

int n2 = 6;

m = median(x2,n2);

cout << m << endl;

}

Step-by-step explanation:

The main program contains the examples given in the question.

Function Explanation: The function int median(int x[], int n) takes two arguments, one is the array x and the other is the size of the array n.

First, the function sorts the elements in ascending order.

After that, it is calculated whether n is even or odd. If n is an even number, The middle numbers can be obtained as follows:

Divide n by 2 to get the first middle element.

The second middle element is the element before first middle element, therefore

x[ (n/2 )-1] + x[n/2] gives us the sum of middle elements, where as dividing it by 2 gives us the avg of the two numbers.

If n is an odd number, than the middle element can be simply returned by dividing n by 2.

The working of the program is as follows

Array 1: 5 8 1 9 7

After sorting, it becomes: 1,5,7,8,9.

Array indices are : 0,1,2,3,4. Middle element is at index 2, n = 5, therefore n/2 = 2.5 (This is rounded down to 2 because result is stored in integer)

Array 2: 3 7 1 4 6 9

After sorting, it becomes: 1 3 4 6 7 9

Array indices are : 0,1,2,3,4,5. Middle element is at index 2 and 3,n = 6, therefore it can be obtained by n/2-1 and n/2 (n/2 = 3 and n/2 - 1 = 2)

User Jared S
by
6.1k points