Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

WRITE THE CODE IN C++ Write a function called median that returns the median ent

ID: 3575335 • Letter: W

Question

WRITE THE CODE IN C++

Write a function called median that returns the median entry in a 1-dimensional array of integers. For example, if we have an array a={3,4,5,1,6}; then the median entry of this array a is 4.

If the array size is even, it means that array has even number of elements. For example, a={3,2,4,1}, then first sort it, a becomes {1,2,3,4}, then the median entry will be the average of 2 and 3, which is 2.5.

a. First ouput should have you sort the array a first

b. then second output find the entry in the middle position.

Explanation / Answer

// C++ code
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include <iomanip>      // std::setw

using namespace std;

double median(int array[], int size)
{
    double m;
    for (int i = 0; i < size; ++i)
    {
      for (int j = 0; j < size; ++j)
      {
         if(array[i] > array[j])
         {
            int t = array[i];
            array[i] = array[j];
            array[j] = t;
         }
      }
    }

    if(size % 2 != 0)
    {
        return array[size/2];
    }
    else
    {
        m = (array[size/2] + array[size/2 -1])/(double)2;
        return m;
    }
}


int main ()
{
int size;
cout << "Enter size of array: ";
cin >> size;

int array[size];
cout << "Enter array: ";
for (int i = 0; i < size; ++i)
{
     cin >> array[i];
}

cout << "Array: ";
for (int i = 0; i < size; ++i)
{
     cout << array[i] << " ";
}

cout << endl << "Median: " << median(array,size) << endl;

return 0;
}


/*
output:

Enter size of array: 5
Enter array: 3 4 5 1 6
Array: 3 4 5 1 6
Median: 4


Enter size of array: 4
Enter array: 3 2 4 1
Array: 3 2 4 1
Median: 2.5


*/