0

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;
}

}

s666
  • 266
  • 1
  • 3
  • 14
  • 2
    Possible duplicate of [Array assignment and reference in Java](https://stackoverflow.com/questions/44732712/array-assignment-and-reference-in-java) –  Oct 01 '19 at 22:50
  • Maybe you should learn to step into your code with a debugger... – B. Go Oct 01 '19 at 22:51

1 Answers1

0

This

int[] result=nums;  

does not make a copy of the array 'nums'; it just means that 'result' and 'nums' are the same array.

So, an operation on 'result' is an operation on 'nums', which is the likely source of your problem.

One fix would be

  int[] result = Arrays.copyOf(nums, nums.length);

(you'll need to 'import java.util.Arrays')

Alternatively, copy it manually:

  int[] result = new int[nums.length];
  for (int k=0; k<nums.length; k++)
      result[k] = nums[k];
  • Many thanks. "a=b" actually assigns reference of array (Pass By Reference?). I believe that instantiable class and interface are the same as array, because they are all reference variables that store addresses. Additionally, I believe System.arraycopy() also works. – s666 Oct 02 '19 at 10:02
  • Yes - an 'array variable' is a reference to the underlying array, so assignment copies the reference. –  Oct 02 '19 at 11:57