I have a function that sorts a given array using the merge sort algorithm. That algorithm calls itself to solve the problem.
public class MergeSort {
public static void mergeSort(int[][] arr, int left, int right) {
// merge two parts
merge(arr, left, mid, right);
// sort the left part
mergeSort(arr, left, mid);
// sort the right part
mergeSort(arr, mid, right);
}
}
Can I reach performance if I encapsulate the arr
parameter in the class? Consider:
public class MergeSort {
int[][] arr;
public void mergeSort(int left, int right) {
// merge two parts
merge(left, mid, right);
// sort the left part
mergeSort(left, mid);
// sort the right part
mergeSort(mid, right);
}
}
So, the arr
parameter is not passing to the stack.
variables reserve a reference to use from ram. It doesn't matter where you define it, if you're using 1 byte of ram it's the same everywhere.
The important thing is that if the developer wants to use this variable in the program, he can use it easily and separate it from other variables.
If you say why parameters are used, it is necessary to understand why functions are used. The simplest functions are to separate the codes you wrote from other codes and to access these codes easily. That's why the parameters exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.