문제

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].

도움이 되었습니까?

해결책

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) {
                                    ^
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top