Sort Array By Parity LeetCode Solution - The Coding Shala

Home >> LeetCode >> Sort Array By Parity

 In this post, we will learn how to solve LeetCode's Sort Array By Parity Problem and will implement its solution in Java.

Sort Array By Parity Problem

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.

Example 1:
Input: [3,1,2,4]
Output: [2,4,3,1]
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Practice this problem on LeetCode(Click Here).

Sort Array By Parity Java Solution

Approach 1

Java Program: 

class Solution {
    public int[] sortArrayByParity(int[] A) {
        int i = 0, j=A.length-1;
        while(i<j){
            if(A[i]%2==1){
                int tmp = A[i];
                A[i] = A[j];
                A[j] = tmp;
            }
            if(A[i]%2==0) i++;
            if(A[j]%2==1) j--;
        }
        return A;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

Maximum Population Year LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala