import java.util.Arrays;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinT extends RecursiveTask<int[][]> {
    private final int[][] array;
    private static final int THRESHOLD = 20;

    public ForkJoinT(int[][] array) {
        this.array = array;
    }

    public int[][] operationMatrixForkJoinPool(){
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinT task = new ForkJoinT(array);
        return pool.invoke(task);
    }

    @Override
    protected int[][] compute() {
        if (array.length <= 1) {
            return array;
        }
        if (array.length <= THRESHOLD) {
            return singleOperationMatrix(array);
        }

        int mid = array.length / 2;
        int[][] leftPart = Arrays.copyOfRange(array, 0, mid);
        int[][] rightPart = Arrays.copyOfRange(array, mid, array.length);

        ForkJoinT leftTask = new ForkJoinT(leftPart);
        ForkJoinT rightTask = new ForkJoinT(rightPart);

        leftTask.fork();
        int[][] right = rightTask.compute();
        int[][] left = leftTask.join();

        return merge(left, right);
    }

    private int[][] singleOperationMatrix(int[][] array) {
        if (array.length <= 1) {
            return array;
        }

        int mid = array.length / 2;
        int[][] left = Arrays.copyOfRange(array, 0, mid);
        int[][] right = Arrays.copyOfRange(array, mid, array.length);

        left = singleOperationMatrix(left);
        right = singleOperationMatrix(right);

        return merge(left, right);
    }

    private int[][] merge(int[][] left, int[][] right) {
        int[][] result = new int[left.length + right.length][];
        int i = 0, j = 0, k = 0;

        while (i < left.length && j < right.length) {
            if (findMaxElementRow(left[i]) >= findMaxElementRow(right[j])) {
                result[k++] = left[i++];
            } else {
                result[k++] = right[j++];
            }
        }

        while (i < left.length) {
            result[k++] = left[i++];
        }
        while (j < right.length) {
            result[k++] = right[j++];
        }

        return result;
    }

    private static int findMaxElementRow(int[] row) {
        int maxCurrentValue = Integer.MIN_VALUE;
        for (int i = 0; i < row.length; i++) {
            maxCurrentValue = (row[i] >= maxCurrentValue ? row[i] : maxCurrentValue);
        }
        return maxCurrentValue;
    }
}