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

Q6) Write a method called GetArrayMedian() that takes a sorted array of doubles

ID: 3766389 • Letter: Q

Question

Q6)

Write a method called GetArrayMedian() that takes a sorted array of doubles as its only parameter, and returns the median value (a double) of the array. It does not print the median value, it returns it. The median value is the value in the middle of the array if there is an odd number of values, but if there is an even number, then it is the average of the two middle values. You can assume the array that is passed has at least one element in it.

public static double GetArrayMedian(doubles [] values)
{




}

Explanation / Answer

Answer :

public static double GetArrayMedian(double[] values)
   {

       // Sort our array
       int[] sortedArr = Arrays.Sort(values);
      
       double median = 0;
      
       // If our array's length is even, then we need to find the average of the two

centered values
       if (values.length % 2 == 0)
       {
           int indexA = (values.length - 1) / 2;
           int indexB = values.length / 2;
          
           median = ((double) (sortedArr[indexA] + sortedArr[indexB])) / 2;
       }
       // Else if our array's length is odd, then we simply find the value at the

center index
       else
       {
           int index = (sortedArr.length - 1) / 2;
           median = sortedArr[ index ];
       }
      
       // Print the values of the sorted array
       for (int v : sortedArr)
       {
               System.out.println(v);
       }
                      
       return median;  
   }