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:
Input: arr[]={3,1,2,4}
Output: arr[]={2,4,3,1}
Approach
Java
import java.util.Arrays;public class SortArrayByParity {public static void main(String[] args) {int arr[] = { 3, 1, 2, 4 };int sortArr[] = sortArrayByParity(arr);System.out.println(Arrays.toString(sortArr));}// given array sort by parityprivate static int[] sortArrayByParity(int[] arr) {int a[] = new int[arr.length];int even = 0;int odd = arr.length - 1;for (int i = 0; i < arr.length; i++) {// for evenif (arr[i] % 2 == 0) {a[even++] = arr[i];}// for oddelse {a[odd--] = arr[i];}}return a;}}
C++
#include <bits/stdc++.h>using namespace std;//sort the array by parityvector<int> sortArrayByParity(vector<int>& A){vector<int> res;//for even numbersfor(int i=0;i<A.size();i++){if(A[i]%2==0){res.push_back(A[i]);}}//for odd numbersfor(int i=0;i<A.size();i++){if(A[i]&1){res.push_back(A[i]);}}return res;}int main(){vector<int> arr={3,1,2,4};vector<int> newArray=sortArrayByParity(arr);for(int i=0;i<newArray.size();i++)cout<<newArray[i]<<" ";return 0;}
No comments:
Post a Comment