Skip to content

Commit 8234266

Browse files
committed
added Sort Array By Parity (easy)
1 parent f0e911a commit 8234266

File tree

4 files changed

+68
-0
lines changed

4 files changed

+68
-0
lines changed

Easy/SortArrayByParity/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
2+
# Sort Array By Parity
3+
[Leetcode Link](https://leetcode.com/problems/sort-array-by-parity/)
4+
5+
## Problem:
6+
7+
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`.
8+
9+
You may return any answer array that satisfies this condition.
10+
11+
## Example:
12+
13+
```
14+
Input: [3,1,2,4]
15+
Output: [2,4,3,1]
16+
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
17+
```
18+
19+
## Note:
20+
21+
- `1 <= A.length <= 5000`
22+
- `0 <= A[i] <= 5000`
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Easy.SortArrayByParity;
2+
3+
/**
4+
*
5+
*/
6+
public class Solution {
7+
8+
public int[] sortArrayByParity(int[] A) {
9+
int evenIndex = -1;
10+
for (int i = 0; i < A.length; i++) {
11+
if (A[i] % 2 != 0) {
12+
// if odd
13+
// initialize first even index
14+
if (evenIndex < 0) {
15+
evenIndex = i;
16+
}
17+
while (evenIndex < A.length-1 && A[evenIndex] % 2 != 0) {
18+
evenIndex++;
19+
}
20+
swap(A, i, evenIndex);
21+
}
22+
}
23+
return A;
24+
}
25+
26+
private void swap(int[] A, int i, int j) {
27+
int temp = A[i];
28+
A[i] = A[j];
29+
A[j] = temp;
30+
}
31+
32+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package Easy.SortArrayByParity;
2+
3+
import java.util.Arrays;
4+
5+
public class TestDriver {
6+
7+
public static void main(String[] args) {
8+
Solution sol = new Solution();
9+
int[] A = {3, 1, 2, 4, 5};
10+
System.out.println("Output: " + Arrays.toString(sol.sortArrayByParity(A)));
11+
}
12+
13+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Languages used: Java and Python
3030
- [Shortest Unsorted Continuous Subarray](Easy/ShortedUnsortedContinuousSubarray)
3131
- [Find Lucky Integer in an Array](Easy/FindLuckyIntegerInArray)
3232
- [N-Repeated Element in Size 2N Array](Easy/N_RepeatedElementInArray)
33+
- [Sort Array By Parity](Easy/SortArrayByParity)
3334
- Medium
3435
- [Minimum Add to Make Parentheses Valid](Medium/MinimumAddtoMakeParenthesesValid)
3536
- [Distribute Coins in Binary Tree](Medium/DistributionCoinsInBinaryTree)

0 commit comments

Comments
 (0)