将数组中的每个元素与其相邻元素交换

我需要写一个程序。此方法将整数数组作为输入并返回数组,其中每个值与其相邻元素交换。如果数组有奇数,则不会交换最后一个元素。


int[] array ={111,77,88,44,32,11,13,25,44}

结果:


    finalarray= 77,111,44,88,11,32,25,13,44

我尝试使用嵌套的 for 循环但没有得到它



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

        for (int i = 1; i < array.length; i++) {

            for (int j = i; j <= i; j++) {

                int temp = array[i - 1];

                array[i - 1] = array[j];

                array[j] = temp;

            }


        }

        for (int k = 0; k < array.length; k++) {

            System.out.print(array[k] + " ");

        }


        //Desired output 17,111,44,88,11,32,25,13,44

        return array;

    }


    public static void main(String args[]) {

        int[] number = { 111, 17, 88, 44, 32, 11, 13, 25, 44 };

        number = swap(number);


    }


千万里不及你
浏览 108回答 3
3回答

慕斯709654

到目前为止你试过的代码在哪里?!反正for (int i = 0; i < array.length; i += 2) {&nbsp; &nbsp; &nbsp; &nbsp; if(i+1 >= array.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int temp = array[i];&nbsp; &nbsp; &nbsp; &nbsp; array[i] = array[i+1];&nbsp; &nbsp; &nbsp; &nbsp; array[i+1] = temp;&nbsp; &nbsp; }

郎朗坤

&nbsp; int[] array ={111,77,88,44,32,11,13,25,44};&nbsp; &nbsp; int[] output = new int[array.length];&nbsp; &nbsp; for(int x = 0; x < array.length - 1; x += 2) {&nbsp; &nbsp; &nbsp; &nbsp; output[x] = array[x + 1];&nbsp; &nbsp; &nbsp; &nbsp; output[x+1] = array[x];&nbsp; &nbsp; }&nbsp; &nbsp; if(array.length % 2 != 0) {&nbsp; &nbsp; &nbsp; &nbsp; output[output.length-1] = array[array.length-1];&nbsp; &nbsp; }您只需遍历数组,并用交换的值填充新数组。

胡子哥哥

这应该可以解决问题!public static final <T> void swap (T[] a, int i, int j) {T t = a[i];a[i] = a[j];a[j] = t;}public static final <T> void swap (List<T> l, int i, int j) {Collections.<T>swap(l, i, j);}private void test() {String [] a = {"Hello", "Goodbye"};swap(a, 0, 1);System.out.println("a:"+Arrays.toString(a));List<String> l = new ArrayList<String>(Arrays.asList(a));swap(l, 0, 1);System.out.println("l:"+l);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java