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

}

2
  • 2
    Possible duplicate of Array assignment and reference in Java Commented Oct 1, 2019 at 22:50
  • Maybe you should learn to step into your code with a debugger... Commented Oct 1, 2019 at 22:51

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yes - an 'array variable' is a reference to the underlying array, so assignment copies the reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.