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 en

ID: 3573684 • 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. You need to sort the array a first, to get {1,3,4,5,6}, then find the entry in the middle position. 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.

Explanation / Answer

#include<iostream>
using namespace std;
float median(int a[],int n)//which returns median in a given array
{
   int i,j,k;
  
   //sorting...
   for(i=0;i<n;i++)
   {
       for(j=0;j<n;j++)
       {
           if(a[i]<a[j])
           {
               k=a[i];a[i]=a[j];a[j]=k;//swapping
           }  
       }  
   }
  
   if(n%2==0)
   {
       return (float)(a[n/2]+a[(n-1)/2])/2;   //if length is odd
   }
   return a[n/2];//if length is odd
  
  
}
int main()
{
  
   int a[]={3,4,5,1,6};
  
   cout<<"The median is "<<median(a,5)<<endl;
  
   return 0;
}

ouput:-

The median is 4


Process exited normally.
Press any key to continue . . .