在 Java 中反转数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13465385/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:51:22  来源:igfitidea点击:

Reverse an array in Java

javaarraysreverse

提问by Ralph

I am trying to reverse an array in 2 ways:

我试图以两种方式反转数组:

1) By creating a new array which was very easy:

1)通过创建一个非常简单的新数组:

public static int[] reverse(int[] array) {
    int[] reverseArray = new int[array.length];
    for(int i = 0; i < reverseArray.length; i++) {
        reverseArray[i] = array[array.length - i - 1];
    }
    return reverseArray;
}

2) The second method I got my answer but I actually don't understand it very well, it actually makes use of swapping, giving the value of the array to a temporary variable then changes it and returns it to the original variable:

2)第二种方法我得到了我的答案,但我实际上不太了解它,它实际上利用了交换,将数组的值赋予一个临时变量,然后更改它并将其返回到原始变量:

public static int[] reverse2(int[] array)
{
    for (int i=0; i < array.length / 2; i++)
    {   
        int temp = array[i];
        array[i] = array[array.length - i - 1];
        array[array.length - i - 1] = temp;
    }
    return array;
}

Could someone explain to me the second code? I don't understand the division by 2? What happens if the array size is even or odd?

有人可以向我解释第二个代码吗?我不明白除以 2?如果数组大小是偶数或奇数会发生什么?

回答by awolfe91

The division by 2 is merely so you only go through the first half of the array. If you swap the first and last items, you don't want to do it again when i reaches array.length. If the size is even, it will stop before the second half, if the size is odd, it will stop before the center position, which doesn't need to be switched anyway. Hope that helps!

除以 2 只是让您只遍历数组的前半部分。如果你交换了第一项和最后一项,当我到达 array.length 时你不想再做一次。如果大小为偶数,则在下半场之前停止,如果大小为奇数,则在中心位置之前停止,无论如何都不需要切换。希望有帮助!

回答by Jon Newmuis

Imagine your array is this:

想象一下你的数组是这样的:

[ 1 2 3 4 5 ]

The second solution you've posted works as follows:

您发布的第二个解决方案的工作原理如下:

[ 1 2 3 4 5 ]
  ^--swap-^

[ 5 2 3 4 1 ]
    ^swp^

[ 5 4 3 2 1 ]

As you can see, you only need to traverse halfof the array for this to work (hence making it perform better than the first solution, where you need to traverse the whole thing). This is where the division by two comes in; halfof the array equates to only needing to check elements up to array.length / 2.

如您所见,您只需要遍历数组的一半即可使其工作(因此使其性能优于第一个解决方案,在第一个解决方案中您需要遍历整个数组)。这就是二分法的用武之地;数组的一半相当于只需要检查最多array.length / 2.

For an even number of elements, it will do the same thing, only swapping the innermost pair as well:

对于偶数个元素,它会做同样的事情,只交换最里面的一对:

[ 1 2 3 4 5 6 ]
  ^--swap---^

[ 6 2 3 4 5 1 ]
    ^swap-^

[ 6 5 3 4 2 1 ]
      ^-^

[ 6 5 4 3 2 1 ]

回答by neilvillareal

The division by 2 just means that you don't have to loop through all the elements in the array. Since you are reversing the array, while the loop is at the first element, it means that it should just swap it with the first element from the other end.

除以 2 只是意味着您不必遍历数组中的所有元素。由于您正在反转数组,而循环位于第一个元素,这意味着它应该只与另一端的第一个元素交换它。

Basically the division by 2 is just to reduce the number of passes of the loop. Think of it as a performance enhancement.

基本上除以 2 只是为了减少循环的次数。将其视为性能增强。

The loop still works fine regardless if the number of elements in the array is odd or even. If the number of elements is odd, the loop stops before the middle element.

无论数组中的元素数量是奇数还是偶数,循环仍然可以正常工作。如果元素数为奇数,则循环在中间元素之前停止。

回答by adchilds

The array is divided by two because you will swap positions 0 and n, 1 and n-1, etc. If the array has an odd amount of values, the last value should be directly in the center of the array and will not need to be swapped. We can loop over the array size divided by n because only n/2 swaps need to happen.

数组除以二是因为您将交换位置 0 和 n、1 和 n-1 等。如果数组有奇数个值,最后一个值应该直接在数组的中心,不需要被交换。我们可以循环遍历除以 n 的数组大小,因为只需要进行 n/2 次交换。

回答by Mjachowdhury

Simple and quick...

简单快捷...

public class ReverseAnIntegerArray {
static void reverseAnArray(int[] arrNum) {
    System.out.println("Original Array :" + Arrays.toString(arrNum));

    for (int i = arrNum.length - 1; i >= 0; i--) {
        System.out.print(arrNum[i] + " ");
    }

}

public static void main(String[] args) {
    int myArr[] = { 1, 2, -3, 4, 5, 34, 50 };
    reverseAnArray(myArr);
}

}

Out put will be - Original Array :[1, 2, -3, 4, 5, 34, 50]

输出将是 - 原始数组 :[1, 2, -3, 4, 5, 34, 50]

50 34 5 4 -3 2 1

50 34 5 4 -3 2 1

回答by user3368996

The divide by 2 won't work entirely. It will only work if you have an odd number of integers.

除以 2 不会完全起作用。它仅在您有奇数个整数时才有效。

For instance:

例如:

Give me an integer that would represent the length of an array: 5

给我一个代表数组长度的整数:5

Enter 5 value(s)

输入 5 个值

Value #0: 1

值 #0:1

Value #1: 2

值 #1:2

Value #2: 3

值 #2:3

Value #3: 4

值 #3:4

Value #4: 5

值 #4:5

Your current array: 1 | 2 | 3 | 4 | 5 |

您当前的数组:1 | 2 | 3 | 4 | 5 |

Your array reversed: 5 | 4 | 3 | 2 | 1 | BUILD SUCCESSFUL (total time: 11 seconds)

你的数组颠倒了:5 | 4 | 3 | 2 | 1 | 构建成功(总时间:11 秒)

Now, if you were to put in an even number integers, let's say 6, this is what would happen:

现在,如果您要输入偶数整数,例如 6,将会发生以下情况:

Give me an integer that would represent the length of an array: 6

给我一个代表数组长度的整数:6

Enter 6 value(s)

输入 6 个值

Value #0: 1

值 #0:1

Value #1: 2

值 #1:2

Value #2: 3

值 #2:3

Value #3: 4

值 #3:4

Value #4: 5

值 #4:5

Value #5: 6

值 #5:6

Your current array: 1 | 2 | 3| 4| 5 | 6 |

您当前的数组:1 | 2 | 3| 4| 5 | 6 |

Your array reversed: 6 | 5 | 3| 4| 2 | 1 | BUILD SUCCESSFUL (total time: 5 seconds)

你的数组颠倒了:6 | 5 | 3| 4| 2 | 1 | 构建成功(总时间:5 秒)

Source code:

源代码:

/* Write a program that prompts the user for an integer that would represent the length of an array, then asks the user to enter that many values. Store these values in an array and print the array. Then reverse the array elements so that the first element becomes the last element, the second element becomes the second to last element, and so on, with the old last element now first. Do not just reverse the order in which they are printed; actually change the way they are stored in the array. Do not create a second array; just rearrange the elements within the array you have. (Hint: Swap elements that need to change places.) When the elements have been reversed, print the array again. */

/* 编写一个程序,提示用户输入一个表示数组长度的整数,然后要求用户输入这么多值。将这些值存储在一个数组中并打印该数组。然后反转数组元素,使第一个元素成为最后一个元素,第二个元素成为倒数第二个元素,依此类推,旧的最后一个元素现在排在第一位。不要只是颠倒它们的打印顺序;实际上改变了它们在数组中的存储方式。不要创建第二个数组;只需重新排列您拥有的数组中的元素。(提示:交换需要改变位置的元素。)当元素被反转后,再次打印数组。*/

package reversinganarray;

包反向数组;

import java.util.Scanner;

导入 java.util.Scanner;

public class ReversinganArray {

公共类 ReversinganArray {

public static void main(String[] args) {
    int i = 0;
    Scanner input = new Scanner(System.in);
    System.out.print("Give me an integer that would represent the length of an array: ");
    int integer = input.nextInt();
    int[] test = new int[integer];
    System.out.println("Enter " + integer + " " + "value(s)");
    while (i < integer) {
        System.out.println("Value #" + i + ": ");
        test[i] = input.nextInt();
        i++;
    }
    System.out.print("Your current array: ");
    i = 0;
    while (i < integer) {
        System.out.print(test[i] + " | ");
        i++;
    }
    i = 0;
    while (i <= integer / 2) {
        int temp = test[i]; //a = b
        test[i] = test[(integer - i - 1)]; //b = c
        test[(integer - i - 1)] = temp;// c = a
        i++;
    }
    System.out.println("");
    System.out.print("Your array reversed: ");
    i = 0;
    while (i <= integer - 1) {
        System.out.print(test[i] + " | ");
        i++;
    }
}

}

}

I happen to be trying to figure this problem out myself...

我碰巧试图自己解决这个问题......