I am a little confused and was looking for some clarification, so I am studying data structures and algorithms and was working on merge sort. Essentially I wanted to return the sorted list and print it to test to see if I had implemented the code correctly, however the lazy scientict I am decided not to copy the data back into the original array and instead just return the temp array. I noticed when I return temp at the end I'll get a different answer than if I returned the original array (named a) after copying back. Was wondering if someone could explain why this occurs. Thank you! Below is the code with the proper print, if you change the return to temp in the merge method you will notice the list stops sorting properly
public class mergeSort {
public static void main(String[] args) {
int[] a = new int[10];
for(int i = 0; i < a.length; i++) {
a[i] = (int)(Math.random()*30+1);
System.out.println(i + ": " + a[i]);
}
mergeSort(a);
}
public static void mergeSort(int[] a) {
int[] temp = new int[a.length];
a = mergeSort(a, 0, a.length, temp);
for(int i = 0; i < a.length; i++){
System.out.println(a[i]);
}
}
public static int[] mergeSort(int[] a, int start, int end, int[] temp) {
int mid;
//Recursive method
if(1 < end-start) {
mid = start + (end-start)/2;
mergeSort(a, start, mid, temp);
mergeSort(a, mid, end, temp);
a = merge(a, start, mid, end, temp);
}
return a;
}
public static int[] merge(int[] a, int start, int mid, int end, int[] temp) {
int currL = start;
int currR = mid;
int currT;
for(currT = start; currT < end; currT++) {
if(currL < mid && (currR >= end || a[currL] < a[currR])) {
temp[currT] = a[currL];
currL++;
}
else{
temp[currT] = a[currR];
currR++;
}
}
for(currT = start; currT < end; currT++) {
a[currT] = temp[currT];
}
return a;
}
}