Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers in it. Create two arrays with size calculated after traversing and start storing them.
Below is the implementation of the above approach:
Java
// Java Program to Store Even & Odd // Elements of an Array into Separate Arrays public class Even_Odd {
// Print array method
public static void printArray( int [] array)
{
for ( int i = 0 ; i < array.length; i++)
System.out.print(array[i] + " " );
System.out.println();
}
public static void main(String[] args)
{
int n = 8 ;
// array with N size
int array[] = { 23 , 55 , 54 , 9 , 76 , 66 , 2 , 91 };
int evenSize = 0 ;
int oddSize = 0 ;
for ( int i = 0 ; i < n; i++) {
if (array[i] % 2 == 0 )
evenSize++;
else
oddSize++;
}
// odd and even arrays with size
int [] even = new int [evenSize];
int [] odd = new int [oddSize];
// odd and even array iterator
int j = 0 , k = 0 ;
for ( int i = 0 ; i < n; i++) {
if (array[i] % 2 == 0 )
even[j++] = array[i];
else
odd[k++] = array[i];
}
// print array method
System.out.print( "Even Array contains: " );
printArray(even);
System.out.print( "Odd Array contains: " );
printArray(odd);
}
} |
Output:
Even Array contains: 54 76 66 2 Odd Array contains: 23 55 9 91
Time Complexity: O(n)
Space Complexity: O(n)