Question

public static void swap(int [] array) {
    for (int i = 0; i < array.length-1; i++) {
        int temp = array[i+1];
        array[i+1] = array[i];
        array[i]=temp;
    }
}

I want to swap each neighboring element by twos. This code gives me [2, 3, 4, 5, 6, 1] instead of [2, 1, 4, 3, 6, 5].

Was it helpful?

Solution

Just increment by 2, since you essentially want to swap every other pair of consecutive elements:

for (int i = 0; i < array.length-1; i += 2) {
                                    ^
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top