package savinov_roman_lab_1;

public class MergeSortThreadLess {

    public static void mergeSort(int[][] array, int left, int right) {
        if (left < right) {
            int middle = (left + right) / 2;
            mergeSort(array, left, middle);
            mergeSort(array, middle + 1, right);
            merge(array, left, middle, right);
        }
    }

    protected static void merge(int[][] array, int left, int middle, int right) {
        int n1 = middle - left + 1;
        int n2 = right - middle;

        int[][] leftArray = new int[array.length][n1];
        int[][] rightArray = new int[array.length][n2];

        for (int i = 0; i < array.length; i++) {
            System.arraycopy(array[i], left, leftArray[i], 0, n1);
            System.arraycopy(array[i], middle + 1, rightArray[i], 0, n2);
        }

        int i = 0, j = 0, k = left;
        while (i < n1 && j < n2) {
            if (leftArray[0][i] <= rightArray[0][j]) {
                for (int row = 0; row < array.length; row++) {
                    array[row][k] = leftArray[row][i];
                }
                i++;
            } else {
                for (int row = 0; row < array.length; row++) {
                    array[row][k] = rightArray[row][j];
                }
                j++;
            }
            k++;
        }

        while (i < n1) {
            for (int row = 0; row < array.length; row++) {
                array[row][k] = leftArray[row][i];
            }
            i++;
            k++;
        }

        while (j < n2) {
            for (int row = 0; row < array.length; row++) {
                array[row][k] = rightArray[row][j];
            }
            j++;
            k++;
        }
    }
}
