3.30 Sort Array By Parity
3.30.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 905
- Difficulty: Easy
- URL: https://leetcode.com/problems/sort-array-by-parity/
- Tags:
- Techniques: Two Pointers, Array
3.30.2 Description
Given an array A of non-negative integers, return any array consisting of all the even elements of A followed by all the odd elements.
3.30.5 Solution - Two Pointers
3.30.5.1 Walkthrough
Use two pointers. Advance left until an odd number is found and decrement right until an even number is found; swap them and continue until the pointers cross.
3.30.5.3 Implementation Steps
- Set
left = 0,right = A.length - 1. - While
left < right:- Increment
leftwhileA[left]is even. - Decrement
rightwhileA[right]is odd. - If
left < right, swapA[left]andA[right].
- Increment
- Return
A.
3.30.5.4 Code - Java
public int[] sortArrayByParity(int[] A) {
int left = 0;
int right = A.length - 1;
while (left < right) {
while (left < right && (A[left] & 1) == 0) {
left++;
}
while (left < right && (A[right] & 1) == 1) {
right--;
}
if (left < right) {
int temp = A[left];
A[left] = A[right];
A[right] = temp;
}
}
return A;
}