How to skip certain array indexes? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to skip certain array indexes? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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;
}
We are here to answer your question about How to skip certain array indexes? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji