Java Program to Sort Even Numbers in an Array
Here's a Java program that sorts only the even numbers in an array while leaving the odd numbers in their original positions:
import java.util.ArrayList;
import java.util.Collections;
public class SortEvenNumbers {
public static void main(String[] args) {
int[] array = {3, 2, 4, 1, 5, 7, 6, 8, 9, 0};
System.out.println("Original array:");
printArray(array);
sortEvenNumbers(array);
System.out.println("\nArray after sorting even numbers:");
printArray(array);
}
public static void sortEvenNumbers(int[] array) {
// Extract even numbers and their positions
ArrayList<Integer> evenNumbers = new ArrayList<>();
ArrayList<Integer> evenPositions = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 0) {
evenNumbers.add(array[i]);
evenPositions.add(i);
}
}
// Sort the even numbers
Collections.sort(evenNumbers);
// Place the sorted even numbers back in their original positions
for (int i = 0; i < evenPositions.size(); i++) {
array[evenPositions.get(i)] = evenNumbers.get(i);
}
}
public static void printArray(int[] array) {
for (int num : array) {
System.out.print(num + " ");
}
}
}
How This Program Works:
-
Extracting Even Numbers: The program first scans through the array to identify all even numbers and their positions, storing them in separate ArrayLists.
-
Sorting Even Numbers: The even numbers are then sorted using Java's Collections.sort() method.
-
Replacing Even Numbers: The sorted even numbers are placed back into their original positions in the array.
-
Output: The program prints the original array and the modified array after sorting the even numbers.
Example Output:
For the input array {3, 2, 4, 1, 5, 7, 6, 8, 9, 0}, the output would be:
Original array:
3 2 4 1 5 7 6 8 9 0
Array after sorting even numbers:
3 0 2 1 5 7 4 6 9 8
Notice that the odd numbers (3, 1, 5, 7, 9) remain in their original positions, while the even numbers (2, 4, 6, 8, 0) have been sorted in ascending order.