Java Exercises: Partition an given array of integers into even number first and odd number second
Java Basic: Exercise-176 with Solution
Write a Java program to partition an given array of integers into even number first and odd number second.
Original array: [7, 2, 4, 1, 3, 5, 6, 8, 2, 10]
After partition the said array becomes: [10, 2, 4, 2, 8, 6, 5, 3, 1, 7]
Pictorial Presentation:

Sample Solution:
Java Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] nums = {7, 2, 4, 1, 3, 5, 6, 8, 2, 10};
System.out.println("Original array: "+Arrays.toString(nums));
int[] result = partitionArray2(nums);
System.out.println("After partition the said array becomes: " +Arrays.toString(result));
}
public static int[] partitionArray2(int[] nums) {
int i = 0;
int j = nums.length - 1;
while (i < j) {
while (nums[i] % 2 == 0) i++;
while (nums[j] % 2 != 0) j--;
if (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
return nums;
}
}
Sample Output:
Original array: [7, 2, 4, 1, 3, 5, 6, 8, 2, 10] After partition the said array becomes: [10, 2, 4, 2, 8, 6, 5, 3, 1, 7]
Flowchart:

Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to delete a specified node in the middle of a singly linked list.
Next: Write a Java program to get a new binary tree with same structure and same value of a given binary tree.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Java: Anagrams
Generates all anagrams of a string.
public static List<String> anagrams(String input) { if (input.length() <= 2) { return input.length() == 2 ? Arrays.asList(input, input.substring(1) + input.substring(0, 1)) : Collections.singletonList(input); } return IntStream.range(0, input.length()) .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1))) .flatMap(entry -> anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1)) .stream() .map(s -> entry.getValue() + s)) .collect(Collectors.toList()); }
Ref: https://bit.ly/3rvAdAK
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises