How to sort some elements and leave others in Java?

Viewed 1957

I'm looking to sort some elements within an array but exclude others.

For a simple example, an array containing integers, I would like to sort the odd numbers but leave the even where they are.

So far I have the following:

public class MyClass {
    public static void main(String args[]) {
        int temp;
        int array[] = {5, 3, 2, 8, 1, 4};

        int[] sortedArray = new int[array.length];
        for (int j = 0; j < array.length - 1; j++) {
            for (int x = 0; x < array.length - 1; x++) {
                if (array[x] > array[x + 1] && array[x] % 2 != 0 && array[x + 1] % 2 !=0) {
                    temp = array[x];
                    array[x] = array[x + 1];
                    array[x + 1] = temp;
                    sortedArray = array;
                }
            }
        }
        for (int i: sortedArray) {
            System.out.println(i);
        }

    }
}

Given integer array: 5, 3, 2, 8, 1, 4

Output of the code: 3, 5, 2, 8, 1, 4

Expected output: 1, 3, 2, 8, 5, 4

Can't quite figure out the logic needed for the scenario in which a lower odd number comes before an even number within the original array.

4 Answers
Related