'Why does this merge sort code gives zeroes instead of given elements in the resulting array

When I try to print the left and right subarrays some of the elements become zero instead of actual elements present in the array. The merge function works fine but the sorting function doesn't seem to work.

public static void mergeSort(int[] A) {
    int n = A.length;
    if (n < 2)
        return;
    int mid = n / 2;
    int[] left = new int[mid];
    int[] right = new int[n - mid];
    for (int i = 0; i < mid - 1; i++) {
        left[i] = A[i];
    }
    System.out.println(Arrays.toString(left));
    for (int j = 0; j < n - mid; j++) {
        right[j] = A[j + mid];
    }
    System.out.println(Arrays.toString(right));
    mergeSort(left); 
    mergeSort(right);
    merge(left, right, A);
}

public static void merge(int[] l, int[] r, int[] A) {
    int nl = l.length;
    int nr = r.length;
    int i = 0, j = 0, k = 0;
    while (i < nl && j < nr) {
        if (l[i] <= r[i]) {
            A[k] = l[i];
            i++;
        } else {
            A[k] = r[j];
            j++;
        }
        k++;
    }
    while (i < nl) {
        A[k] = l[i];
        i++;
        k++;
    }
    while (j < nr) {
        A[k] = r[j];
        j++;
        k++;
    }
}


Solution 1:[1]

The loop to initialize the left subarray stops before the last element, you should write:

    for (int i = 0; i < mid; i++) {
        left[i] = A[i];
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chqrlie