交换误用荒谬?

huangapple go评论72阅读模式
英文:

Swap misuse absurdity?

问题

以下是在Java中实现的逆向数组代码。我按照逻辑进行了解析,我觉得它应该能够工作。

public static int[] reverseArray(int[] arr){
    int temp = 0;
    int[] newArr;
    newArr = Arrays.copyOf(arr, arr.length);
    for (int i = 0; i < arr.length - 1; i++){
        temp = newArr[i];
        newArr[i] = newArr[arr.length - 1 - i];
        newArr[arr.length - 1 - i] = temp;
    }
    return newArr;
}

我传入了一个数组 [1, 2, 3, 4, 5]。
它返回给我只有第一个和最后一个数字交换的数组。
返回 [5, 2, 3, 4, 1]。

英文:

the following is a reverse array implementation in java. I walked through it logically and I feel like it should work.

public static int[] reverseArray(int[] arr){
int temp = 0;
int[] newArr;
newArr = Arrays.copyOf(arr, arr.length);
for (int i = 0; i &lt; arr.length - 1; i++){
temp = newArr[i];
newArr[i] = newArr[arr.length - 1 - i];
newArr[arr.length - 1 - i] = temp;
}
return newArr;
}

I pass in an array [1, 2, 3, 4, 5]
It returns to me only the first the the last number swapped.
Returns [5, 2, 3, 4, 1]

答案1

得分: 3

你正在循环直到数组的末尾,这导致你的逻辑失败。

你必须循环到 arr.length/2,而不是循环整个数组。循环整个数组会导致你的程序执行以下操作 -

  • 交换元素并在循环的前半部分反转数组:现在,当循环达到索引 - arr.length/2 时,所有元素已经彼此交换,你的数组已经被反转。
  • 在循环的后半部分重新开始对所有元素进行交换:这实际上开始将数组元素放回到它们原来的位置。当循环达到索引 arr.length - 1 时,你的数组会恢复到原来的形式。

解决方法:

当你达到 arr.length/2 时,只需停止循环,你的程序就会正常运行。因此,reverseArray 函数中的 for 循环应如下所示:

for (int i = 0; i < arr.length/2 ; i++)
英文:

You are looping till the end of Array which causes your logic to fail.

You must loop till arr.length/2 instead of looping the whole array. Looping the whole array will cause your program to do the following -

  • swap elements and reverse the array in first half of loop : Now when the loop reaches the index - arr.length/2, all elements have already been swapped with each other and your Array has been reversed.
  • Reswapping back of all the elements starts in the second half of loop : This effectively starts putting the Array elements back into their original place. When the loop reaches the index arr.length - 1 , your Array is reversed back to the original form it was.

Solution :

Just stop the loop when you reach arr.length/2 and your program will run fine. So your for-loop in reverseArray function should be as follows :

for (int i = 0; i &lt; arr.length/2 ; i++)

答案2

得分: 1

你在两次交换元素。

在你的示例中,当i为1时,你交换了元素1和3。然后当i为3时,你交换了元素3和1,实际上将它们放回了它们最初的位置。

英文:

You are swapping elements twice.

In your example, when i is 1, you swap elements 1 and 3. Then when i is 3, you swap elements 3 and 1, effectively putting them back where they were originally.

huangapple
  • 本文由 发表于 2020年5月30日 05:48:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/62095066.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定