I have a programming assignment where I have to make a method that takes in an array that is split up into subarrays, and merge them. My method works fine but the Integer array that is passed in 'a' is only changed from inside the method, and remains unchanged from the outside.
After looking around on google, I have concluded that it is impossible to change an array parameter, but then I thought about Arrays.sort which does end up changing the array parameter from outside of the method.
How do I change the array that is passed in as a parameter so that it stays changed outside of the method?
/**
* Merge three sorted arrays with these ranges [lo..mid1], [mid1+1..mid2], [mid2+1..hi] into one sorted array.
* Array a has the original input and final sorted input.
* Array aux is the auxiliary array.
*/
public static void Merge(Integer[] a, int lo, int mid1, int mid2, int hi, Integer[] aux) {
int[] arr1 = copyArray(a, lo, mid1);
int[] arr2 = copyArray(a, mid1+1, mid2);
int[] arr3 = copyArray(a, mid2+1, hi);
int i = 0, j = 0, k = 0, idx = 0;
while(i < arr1.length-1 || j < arr2.length-1 || k < arr3.length-1) {
// arr1[i] is the smallest
if(arr1[i] <= arr2[j] && arr1[i] <= arr3[k]) {
System.out.println("i is bigger at " + arr1[i]);
aux[idx] = arr1[i];
i++;
}
// arr2[j] is the smallest
else if(arr2[j] <= arr1[i] && arr2[j] <= arr3[k]) {
System.out.println("j is bigger at " + arr2[j]);
aux[idx] = arr2[j];
j++;
}
// arr3[k] is the smallest
else if(arr3[k] <= arr2[j] && arr3[k] <= arr1[i]) {
System.out.println("k is bigger at " + arr3[k]);
aux[idx] = arr3[k];
k++;
}
idx++;
}
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
System.out.println(Arrays.toString(arr3));
System.out.println(Arrays.toString(aux));
a = aux;
a[0] = 900;
System.out.println("a from Merge method: " + Arrays.toString(a));
}
aux:aux[idx] = arr3[k];Assignment like this won't worka = aux;because Java is pass by value. (Look that up on Google.)