




Sponsored
Sponsored
The two-pointer technique is useful to place even numbers at the beginning and odd numbers at the end in an in-place manner. We start with two pointers, one at the beginning and the other at the end of the array. If the element at the start is even, move the start pointer forward. If the element at the end is odd, move the end pointer backward. Whenever we find an odd number at the start pointer and an even number at the end pointer, we swap them. Continue this process until the two pointers meet.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since no additional data structures are used.
1import java.util.Arrays;
2
3public class SortArrayByParity {
4    public static void sortArrayByParity(int[] nums) {
5        int i = 0, j = nums.length - 1;
6        while (i < j) {
7            if (nums[i] % 2 > nums[j] % 2) {
8                int temp = nums[i];
9                nums[i] = nums[j];
10                nums[j] = temp;
11            }
12            if (nums[i] % 2 == 0) i++;
13            if (nums[j] % 2 == 1) j--;
14        }
15    }
16
17    public static void main(String[] args) {
18        int[] nums = {3, 1, 2, 4};
19        sortArrayByParity(nums);
20        System.out.println(Arrays.toString(nums));
21    }
22}The Java implementation follows a similar logic using swapping mechanism for rearranging the array.
This approach involves creating two separate lists: one for even numbers and one for odd numbers. We traverse the original array and append every even number to the even list and every odd number to the odd list. Finally, concatenate the even list with the odd list to form the result.
Time Complexity: O(n)
Space Complexity: O(n)
1#
This solution in C separates even and odd numbers into different positions on a new array.