Search code examples
javamergesort

What does a[k++] = l[i++] notation mean


I'm trying to figure out this merge function for merge sort, but I don't understand the line a[k++] = l[i++]. Can someone give me the non-reduced version of what that would look like?

public static void merge(int[] a, int[] l, int[] r, int left, int right) {
 
    int i = 0, j = 0, k = 0;
    while (i < left && j < right) {
        if (l[i] <= r[j]) {
            a[k++] = l[i++];
        }
        else {
            a[k++] = r[j++];
        }
    }
    while (i < left) {
        a[k++] = l[i++];
    }
    while (j < right) {
        a[k++] = r[j++];
    }
}

Solution

  • a[k++] = l[i++];
    

    is the same as

    a[k] = l[i];
    k = k + 1;
    i = i + 1;
    

    Suppose k = 3 and i = 5.

    a[k++] = l[i++];
    print(k);
    print(i);
    

    OUTPUT: 4 6

    is the same as

    a[k] = l[i];
    k = k + 1;
    i = i + 1;
    print(k);
    print(i);
    

    OUTPUT: 4 6