Why is the recursive function return not being used?

Asked

Viewed 234 times

1

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

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;
    }
}

2 answers

2


Because array is a reference type. Reference types passed as argument methods are confused with the parameter. Unlike the types by value in which a copy of the object (of the value) is made in the passage from the argument to the method, in this type the copy is the feathers of the reference, 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 what has been passed, so the return is unnecessary.

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

Has more information on reference in another question.

  • I even try to respond fast, but being faster than you is almost impossible @bigown. What time do you sleep even? :-)

  • I wasn’t even here when you were asked :)

1

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

mergeSort(array, inicio, meio);

In other words, you are always manipulating the same vector in memory. You don’t even need to return it at the end of the function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.