I have to Implement a static public method Implement a double median calculation as a static-public method named "medianInception" in the class "Functionality.java The method gets a two-dimensional double array as input parameter and returns a double value.
Signature: medianInception(double[][] array) : double
First the medians of the subarrays are to be calculated. Note that these can be unsorted!
To sort the individual arrays use BubbleSort, InsertionSort or SelectionSort. Their medians are then entered into a new (one-dimensional) array, which in turn calculates the median again and then returns it. If one of the arrays is null or empty, Double.NaN is to be returned.
When querying whether an array is zero or empty, zero must always be queried first, otherwise a NullPointerException will occur!
I can use the Math library
My code:
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
My problem: This would be the calculation of the median in a one-dimensional array. But I just cannot figure out how to implement this for a 2d. I also want the medians of each subarray.
My problem: This would be the calculation of the median in a one-dimensional array. But I just cannot figure out how to implement this for a 2d. I also want the medians of each subarray.
A 2-D array is an array of 1-D arrays. All you need to do is to iterate the 2-D array and store the median of each row into a 1-D array.
public static double[] median(int[][] m) {
double[] result = new double[m.length];
for (int i = 0; i < m.length; i++) {
int middle = m[i].length / 2;
if (m[i].length % 2 == 1) {
result[i] = m[i][middle];
} else {
result[i] = (m[i][middle - 1] + m[i][middle]) / 2.0;
}
}
return result;
}