Sort Array by Parity

Head on over here to try the problem for yourself.

I attempted a two-pointer approach to try and solve it.

Algorithm

The goal is to try to return the parity array in one pass. For this reason, I create a new array result[] and two pointers, evenPtr, pointing to the start of result[] and oddPtr, pointing to the end of result[]. Now I loop over the initial array. If the element encountered is even, it is pushed at evenPtr, and vice versa. The pointers are updated for the next iteration.

Code


public int[] sortByParity(int[] nums) {
  int evenPtr = 0;
  int oddPtr = nums.length - 1;
  int[] result = new int[nums.length];

  for(int i = 0; i < nums.length; i++) {
    if(nums[i] % 2 == 0) result[evenPtr++] = nums[i];
    else result[oddPtr--] = nums[i];
  }

  return result;
}