Wednesday, December 17, 2025
HomeLanguagesJavaJava Program to Store Even & Odd Elements of an Array into...

Java Program to Store Even & Odd Elements of an Array into Separate Arrays

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)

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32455 POSTS0 COMMENTS
Milvus
108 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11957 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12034 POSTS0 COMMENTS
Shaida Kate Naidoo
6957 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6908 POSTS0 COMMENTS
Umr Jansen
6888 POSTS0 COMMENTS