Separate the even and odd elements from the given array.
Example 1:
Input: a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } Output: Odd : [1, 3, 5, 7, 9], Even : [2, 4, 6, 8]
Approach
Java
import java.util.Arrays;
public class OddEvenArray {
public static void main(String[] args) {
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int odd[] = oddFind(a);
int even[] = evenFind(a);
System.out.println("Odd : " + Arrays.toString(odd));
System.out.println("Even : " + Arrays.toString(even));
}
// method to find even number
private static int[] evenFind(int[] a) {
int even[] = new int[a.length];
int ev = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 == 0) {
even[ev++] = a[i];
}
}
// resize the array till length
if (ev < a.length)
return Arrays.copyOf(even, ev);
return even;
}
// method to find odd number
private static int[] oddFind(int[] a) {
int odd[] = new int[a.length];
int ev = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] % 2 != 0) {
odd[ev++] = a[i];
}
}
// resize the array till length
if (ev < a.length)
return Arrays.copyOf(odd, ev);
return odd;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to find even number
vector<int> evenFind(int arr[],int n)
{
vector<int> even;
for (int i = 0; i <n; i++) {
if (arr[i] % 2 == 0) {
even.push_back(arr[i]);
}
}
return even;
}
//function to find odd number
vector<int> oddFind(int arr[],int n)
{
vector<int> odd;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 != 0) {
odd.push_back(arr[i]);
}
}
return odd;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n=sizeof(arr)/sizeof(arr[0]);
vector<int> odd= oddFind(arr,n);
vector<int> even = evenFind(arr,n);
cout<<"Odd : ";
for(int i=0;i<odd.size();i++)
cout<<odd[i]<<" ";
cout<<"Even : ";
for(int i=0;i<even.size();i++)
cout<<even[i]<<" ";
return 0;
}
No comments:
Post a Comment