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;
}
}
I even try to respond fast, but being faster than you is almost impossible @bigown. What time do you sleep even? :-)
– cantoni
I wasn’t even here when you were asked :)
– Maniero