Question 20
Back to Exercise
What is the output of the following Java program?
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class Main {
static class MaxTask extends RecursiveTask<Integer> {
private static final long serialVersionUID = 1L;
final int[] a; final int lo, hi;
MaxTask(int[] a, int lo, int hi) { this.a = a; this.lo = lo; this.hi = hi; }
@Override protected Integer compute() {
if (hi - lo <= 4) { int m = Integer.MIN_VALUE; for (int i = lo; i < hi; i++) m = Math.max(m, a[i]); return m; }
int mid = (lo + hi) / 2;
MaxTask left = new MaxTask(a, lo, mid);
left.fork();
int rightMax = new MaxTask(a, mid, hi).compute();
return Math.max(left.join(), rightMax);
}
}
public static void main(String[] args) {
int[] data = {12, 45, 7, 89, 23, 56, 91, 3, 67, 34, 88, 19, 76, 41};
System.out.println(new ForkJoinPool(2).invoke(new MaxTask(data, 0, data.length)));
}
}
- A 91 Correct
- B 89
- C 88
- D 14
Correct Answer: Option A
The array is split until pieces have at most 4 elements; partial maxima are combined with Math.max.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!