How to skip certain array indexes?

Need to sort only odd values in array, but even values must remain on their places.

Here is my code:

public static int[] sortArray(int[] array) {

    int length = array.length;
    int temp = 0;


    for (int i = 0; i < length; i++) {
        for (int j = 1; j < length - i; j++) {
            if (j > 0 && array[j] % 2 == 0)continue;

                if (array[j - 1] > array[j]){
                    temp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temp;
                }
            }
        }

    return array;
}

input: new int[]{5, 3, 2, 8, 1, 4, 0}

output: [1, 3, 5, 2, 8, 4, 0]

but I need: [1, 3, 2, 8, 5, 4, 0]

How to skip certain indexes in array?

Think this should be connected with continue operator, but I don’t know how to do it.

Answer

Use this code instead:

public static int[] sortArray(int[] array) {

    int length = array.length;

    for (int i = 0; i < length - 1; i++) {
        int k = -1; // The index of last odd element
        for (int j = 0; j < length - i; j++)
            if (array[j] % 2 != 0) {
                if (k >= 0 && array[k] > array[j]) {
                    int temp = array[k];
                    array[k] = array[j];
                    array[j] = temp;
                }
                k = j;
            }
    }

    return array;
}

Leave a Reply

Your email address will not be published. Required fields are marked *