将第一个数组元素与last交换,第二个与second last交换,依此类推 [英] Swapping first array element with last, second with second last and so on

查看:45
本文介绍了将第一个数组元素与last交换,第二个与second last交换,依此类推的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,在这里我必须将第一个值与last交换,将第二个值与倒数第二个交换,依此类推.

I have an array, where I have to swap the first value with last, second with second last, and so on.

我尝试像下面的代码那样进行操作,但是它只能进行一半,用零代替另一半.有人可以解释这是怎么回事吗?

I tried doing it like in the code below, but it only works halfway, replacing the other half with zeros. Could somebody explain what is wrong here, please?

for (i = 0; i < arr.length; i++) {
    temp = arr[i];
    arr[i] = arr[arr.length - 1 - i];
    arr[arr.length - 1 - i] = temp;
}

推荐答案

您有正确的主意,但是您要遍历整个数组,因此请切换第一个和最后一个元素,然后在到达时再返回最后一个(并且每对开关元件都存在相同的问题).到达一半时,应该停止循环:

You have the right idea, but you're iterating over the whole array, so you switch the first and the last elements, and then back again when you reach the last one (and have the same issue for every pair of switched elements). You should stop the loop when you reach half point:

for (i = 0; i < arr.length / 2; i++) { // Here!
     temp = arr[i];
     arr[i]  = arr[arr.length - 1 - i];
     arr[arr.length - 1 - i] = temp;
}

这篇关于将第一个数组元素与last交换,第二个与second last交换,依此类推的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆