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)