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
public class Even_Odd {
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 ;
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++;
}
int [] even = new int [evenSize];
int [] odd = new int [oddSize];
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];
}
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)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!