交换由两个[1,2,3,4,5,6] = [2,1,4,3,6,5]分组的相邻元素

时间:2014-03-26 00:12:14

标签: java arrays swap

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;
    }
}

我想用两个交换每个相邻的元素。此代码为我[2, 3, 4, 5, 6, 1]而不是[2, 1, 4, 3, 6, 5]

1 个答案:

答案 0 :(得分:4)

只需增加2,因为您基本上想要交换每个其他连续元素对:

for (int i = 0; i < array.length-1; i += 2) {
                                    ^