Please look at the code, I got information printed on the screen is: 1:[2,1] 2:[1,1] Why this happens? There isn't any operation on nums[1] between these two System.out.println(), but the value of nums[1] changed.
public class SortingAlgorithm {
public static void main(String[] args) {
int[] nums= {2,1};
int l=0, h=nums.length-1;
int[] final_result=mergeSort(nums,l,h);
}
public static int[] mergeSort(int[] nums,int l, int h) {
if(l<h) {
int m=(l+h)/2;
nums=merge(nums,l,h,m);
}
return nums;
}
public static int[] merge(int[] nums,int l, int h, int m) {
int[] result=nums;
int k=m+1, idx=0;
while(l<=m && k<=h) {
if(nums[l]<nums[k]) {
result[idx]=nums[l];
l++;
}
else{
System.out.println("1:"+Arrays.toString(nums));
result[idx]=nums[k];
System.out.println("2:"+Arrays.toString(nums));
k++;
}
idx++;
}
while(l<=m) {
result[idx]=nums[l];
l++;
idx++;
}
while(k<=h) {
result[idx]=nums[k];
k++;
idx++;
}
return result;
}
}