I have a large array that I need to calculate the average median with. I have to use recursion, no loops, and no dot operations except for .length.
The array has to be broken up to 3 pieces at most, and the way to break it up is:
I'm getting stumped with how the recursion is supposed to work once the array surpasses the smaller values. This is what I have thus far,
public static double medianAverage(double a, double b, double c) {
if ((a < b && b < c) || (c < b && b < a))
return b;
else if ((b < a && a < c) || (c < a && a < b))
return a;
else if(a == c) return b;
else if(b == c) return a;
else if(a == b) return c;
else
return c;
}
/**
* @return Returns median average
*/
public static double medianHelper(int[] a, int range, int start, int end) {
double avg = 0;
int n = range / 3;
// Base Cases:
if(range == 1) return a[start];
if(range == 2) return (a[start] + a[start + 1]) / 2.0;
if(range == 3) return medianAverage(a[start], a[start + 1], a[start + 2]);
if(range > 3) {
if(range % 3 == 0) {
double p1 = medianHelper(a, n, start, n);
double p2 = medianHelper(a, n, n, n * 2);
double p3 = medianHelper(a, n, n * 2, n * 3);
return medianAverage(p1, p2, p3);
}
if(range % 3 == 1) {
// TODO: Implement
}
if(range % 3 == 2) {
// TODO: Implement
}
}
return avg;
}
public static double median3(int[] a) {
return medianHelper(a, a.length, 0, a.length);
}
Any help at all is appreciated, thank you.
range = 3n
. According to the rules, you can divide the array into [0, n]
, [n + 1, 2n]
and [2n + 1, 3n]
. Each piece has the size n
in this case. range = 3n + 1
. According to the rules, you can divide the array into [0, n]
, [n + 1, 2n + 1]
and [2n + 2, 3n + 1]
. The size of first and last piece is n
and size of the middle piece is n + 1
. range = 3n + 2
. According to the rules, you can divide the array into [0, n + 1]
, [n + 2, 2n + 1]
and [2n + 2, 3n + 2]
. The size of first and last piece is n + 1
and the size of the middle piece is n
. Once you divide the array into 3 pieces like this, you can recursively try to find medians of each piece. I'm confused what you want to do with the medians, but I'll let you figure it out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.