w3resource

Java: Rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers

Java Basic: Exercise-94 with Solution

Write a Java program to rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers.

Pictorial Presentation:

Java Basic Exercises: Rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers

Sample Solution:

Java Code:

import java.util.*;

public class Exercise94 {
    public static void main(String[] args) {
        // Define an array of integers
        int[] array_nums = {1, 7, 8, 5, 7, 13, 0, 2, 4, 9};
        
        // Initialize an index variable to track even numbers
        int i = 0;

        // Display the original array
        System.out.println("Original Array: " + Arrays.toString(array_nums));

        // Find the first odd number's index (i)
        while (i < array_nums.length && array_nums[i] % 2 == 0)
            i++;
        
        // Rearrange the array such that odd numbers come after even numbers
        for (int j = i + 1; j < array_nums.length; j++) {
            if (array_nums[j] % 2 != 0) {
                // Swap even and odd numbers
                int temp = array_nums[i];
                array_nums[i] = array_nums[j];
                array_nums[j] = temp;
                i++;
            }
        }

        // Display the modified array
        System.out.println("New Array: " + Arrays.toString(array_nums));
    }
}

Sample Output:

Original Array: [1, 7, 8, 5, 7, 13, 0, 2, 4, 9]                        
New Array: [7, 5, 7, 13, 9, 1, 0, 2, 4, 8]

Flowchart:

Flowchart: Java exercises: Rearrange all the elements of an given array of integers so that all the odd numbers come before all the even numbers

Java Code Editor:

Previous: Write a Java program to test if an array of integers contains an element 10 next to 10 or an element 20 next to 20, but not both.
Next: Write a Java program to create an array (length # 0) of string values. The elements will contain "0", "1", "2" … through ... n-1.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.