Sort Array By Parity

Question

Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A.

You may return any answer array that satisfies this condition.

Example 1:

Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Note:

  1. 1 <= A.length <= 5000
  2. 0 <= A[i] <= 5000

Solution:

class Solution {
 public int[] sortArrayByParity(int[] A) {

  int[] result = new int[A.length];
  int firstIndex = 0;
  int lastIndex = A.length - 1;



  for (int i = 0; i < A.length; i++) {

   if (A[i] % 2 == 0) {

    result[firstIndex++] = A[i];
   } else {

    result[lastIndex--] = A[i];
   }
  }
  return result;
 }
}

Test Cases

Test Case Expected Result
Input array is empty Empty output
Input array is null Output throws exception (not handled in this program)
Input array has a mix of positive even and odd integer including 0. All even integers, including 0 is followed by odd integers
Input array has both even and odd repetitive integers Output does not ignore repetition and has even integers before odd integers
Input array has only even integers Output Array integers are same as input Array integers
Input array has only odd integers Output Array integers are same as input Array integers
Input Array with one element Output Array same as Input
Input Array with even integers already before odd integers element. Output Array integers same as Input
Input Array with even integers at the last index and odd integers at first index of the array. Output has all even integers first followed by odd integers
TODO Input Array has negative even and odd integers (regression testing) Output of this condition may depend on the requirement and the purpose of this module. For eg. throw an error message for invalid input or process the elements ignoring their sign
TODO Input array has Integer’s MAX and MIN value in its element.(regression) Output will depend on the requirement. For eg throw a message stating invalid input or perform the sort operation with or without error message
Input array is very large including zeroes Output Array has all even integers first followed by odd integers

See also