Sort Array By Parity

Sort Array By Parity

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

LeetCode Problem - 905

class Solution {
    public int[] sortArrayByParity(int[] nums) {
        // Initialize a new array to store the sorted numbers.
        int[] newArr = new int[nums.length];

        // Counter to keep track of the position to insert numbers into the new array.
        int count = 0;

        // First loop to insert even numbers into the new array.
        for(int i=0; i<nums.length; i++){
            if(nums[i]%2==0){
                newArr[count] = nums[i]; // Insert even number at current position.
                count++; // Move to the next position.
            }
        }

        // Second loop to insert odd numbers into the new array.
        for(int i=0; i<nums.length; i++){
            if(nums[i]%2!=0){
                newArr[count] = nums[i]; // Insert odd number at current position.
                count++; // Move to the next position.
            }
        }

        // Return the sorted array.
        return newArr;
    }
}