0

I noticed that when I increment evenNumberIndex before passing it into the swap function, I get different values than when I increment it within the function. Why is this?

public static void main(String[] args) {
      int[] example = {3, 1, 2, 4};

      sortArrayByParity(example);
}
    
public static int[] sortArrayByParity(int[] A) {

     // Keep track of even numbers
     int evenNumberIndex = 0;
        
     // Loop through entire array
     for (int i = 0; i < A.length; i++) {
        // Check for even numbers
        if (A[i] % 2 == 0) {
           swap(A, evenNumberIndex++, i);
        }
     }
        
     return A;
}
    
    
public static void swap(int[] nums, int index1, int index2) {

    System.out.println(index1);
    System.out.println(index2);
    int temp = nums[index1];
    nums[index1] = nums[index2];
    nums[index2] = temp;
}

evenNumberIndex values when incrementing before function: 1, 2

evenNumberIndex values when incrementing inside function: 0, 1

  • Take a look how exactly `++` works – Ecto Aug 09 '20 at 22:43
  • Does this answer your question? [How do the post increment (i++) and pre increment (++i) operators work in Java?](https://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java) – Hawk Aug 09 '20 at 23:04
  • The difference is that they are two different variables. – user207421 Aug 09 '20 at 23:50

0 Answers0