Skip to content

Commit 1ba2e11

Browse files
Arrays: 905. Sort Array By Parity
1 parent be27ab9 commit 1ba2e11

2 files changed

Lines changed: 106 additions & 0 deletions

File tree

.talismanrc

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
fileignoreconfig:
2+
- filename: src/arrays/easy/SortArrayByParity.java
3+
checksum: b8c133e71c80cf6b4d4354d6316099b2da88a22ef24e6ccd46e043ccf908cc1f
4+
version: ""
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package arrays.easy;
2+
3+
import java.util.Arrays;
4+
5+
/***
6+
* Problem 905 in Leetcode: https://leetcode.com/problems/sort-array-by-parity/
7+
*
8+
* Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.
9+
* Return any array that satisfies this condition.
10+
*
11+
* Example 1:
12+
* Input: nums = [3,1,2,4]
13+
* Output: [2,4,3,1]
14+
*
15+
* Example 2:
16+
* Input: nums = [0]
17+
* Output: [0]
18+
*/
19+
20+
public class SortArrayByParity {
21+
public static void main(String[] args) {
22+
int[] nums = {3, 1, 2, 4};
23+
24+
System.out.println("Even and Odd arrays approach: " + Arrays.toString(sortArray(nums)));
25+
System.out.println("Two Pass approach: " + Arrays.toString(sortArrayTwoPass(nums)));
26+
System.out.println("In place approach: " + Arrays.toString(sortArrayInPlace(nums)));
27+
}
28+
29+
private static int[] sortArray(int[] nums) {
30+
int n = nums.length;
31+
int[] evens = new int[n];
32+
int[] odds = new int[n];
33+
int even = 0, odd = 0;
34+
35+
for (int num : nums) {
36+
if ((num & 1) == 0) {
37+
evens[even++] = num;
38+
} else {
39+
odds[odd++] = num;
40+
}
41+
}
42+
43+
int[] result = new int[n];
44+
int index = 0, traverse = 0;
45+
46+
while (traverse < even) {
47+
result[index++] = evens[traverse++];
48+
}
49+
50+
traverse = 0;
51+
52+
while (traverse < odd) {
53+
result[index++] = odds[traverse++];
54+
}
55+
56+
return result;
57+
}
58+
59+
private static int[] sortArrayTwoPass(int[] nums) {
60+
int[] result = new int[nums.length];
61+
int index = 0;
62+
63+
for (int num : nums) {
64+
if ((num & 1) == 0) {
65+
result[index++] = num;
66+
}
67+
}
68+
69+
for (int num : nums) {
70+
if ((num & 1) == 1) {
71+
result[index++] = num;
72+
}
73+
}
74+
75+
return result;
76+
}
77+
78+
private static int[] sortArrayInPlace(int[] nums) {
79+
int start = 0, end = nums.length - 1;
80+
81+
while (start < end) {
82+
if ((nums[start] & 1) == 1) {
83+
swap(nums, start, end);
84+
end--;
85+
} else if ((nums[end] & 1) == 0) {
86+
swap(nums, start, end);
87+
start++;
88+
} else {
89+
start++;
90+
end--;
91+
}
92+
}
93+
94+
return nums;
95+
}
96+
97+
private static void swap(int[] nums, int start, int end) {
98+
int temp = nums[start];
99+
nums[start] = nums[end];
100+
nums[end] = temp;
101+
}
102+
}

0 commit comments

Comments
 (0)