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