Untitled

 avatar
unknown
plain_text
2 months ago
776 B
3
Indexable
public class SortArrayByParity {
    public static int[] sortArrayByParity(int[] nums) {
        int i = 0; // Pointer for placing even numbers

        for (int j = 0; j < nums.length; j++) {
            if (nums[j] % 2 == 0) { // If even, swap with nums[i]
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
                i++; // Move i to the next position
            }
        }
        return nums;
    }

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

        // Print the output
        System.out.print("Output: ");
        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}
Editor is loading...
Leave a Comment