Why is not the recursive function return being used?

1

What happens when I call a function, recursively, without assigning its return to a variable? Why is it not necessary, in this case, to explicitly assign the mergeSort function to the array variable?

public static int[] mergeSort(int[] array, int inicio, int fim) {
        if (fim <= inicio) {
            return array;
        }
        int meio = (inicio + fim) / 2;
        mergeSort(array, inicio, meio);
        mergeSort(array, meio + 1, fim);
        int[] A = new int[meio - inicio + 1];
        int[] B = new int[fim - meio];
        for (int i = 0; i <= meio - inicio; i++) {
            A[i] = array[inicio + i];
        }
        for (int i = 0; i <= fim - meio - 1; i++) {
            B[i] = array[meio + 1 + i];
        }
        int i = 0;
        int j = 0;
        for (int k = inicio; k <= fim; k++) {
            if (i < A.length && j < B.length) {
                if (A[i] < B[j]) {
                    array[k] = A[i++];
                } else {
                    array[k] = B[j++];
                }
            } else if (i < A.length) {
                array[k] = A[i++];
            } else if (j < B.length) {
                array[k] = B[j++];
            }
        }
        return array;
    }
}
    
asked by anonymous 05.12.2015 / 21:34

2 answers

2

Because array is a type by reference. And reference types passed as method arguments become confused with the parameter. Unlike the value types in which a copy of the object (of the value) is done in passing the argument to the method, in this type the copy is the reference's pen, the object remains the same.

Then any changes you make to the received parameter will be reflected in the argument. You are not changing a copy, but rather what was last. So the return is unnecessary.

The return would only be necessary if the ordering was done in another array , as it is being done in-place (in the same array past), the return is redundant. I would particularly make this method return void .

You have more reference information in another question .

    
05.12.2015 / 21:49
1

This happens because the variable array is of type int [] . This is a vector and every vector in Java is an object. This way, whenever you call the mergeSort function in a recursive way as shown below, the reference of that vector is passed ( via pass-by-value ) to the next recursive call.

mergeSort(array, inicio, meio);

In other words, you are always manipulating the same vector in memory. You do not even have to return it at the end of the function.

    
05.12.2015 / 21:50