反向阵列到位 [英] reverse array in place

查看:113
本文介绍了反向阵列到位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此功能reverseArrayInPlace无法正常工作?我只想简单地执行函数所说的内容-反转元素的顺序,以使结果最终在同一数组arr中.我选择通过在函数中使用两个数组来执行此操作.到目前为止,它只是按顺序返回元素...

Why won't this function reverseArrayInPlace work? I want to do simply what the function says - reverse the order of elements so that the results end up in the same array arr. I am choosing to do this by using two arrays in the function. So far it just returns the elements back in order...

    var arr = ["a","b","c","d","e","f"]
    var arr2 = []

    var reverseArrayInPlace = function(array){

      var arrLength = array.length
      for (i = 0; i < arrLength; i++) {
        arr2.push(array.pop())
        array.push(arr2.shift())
      }
    }

    reverseArrayInPlace(arr)

推荐答案

这是一种使用就地算法反转数组的简单方法

Here's a simpler way of reversing an array, using an in-place algorithm

function reverse (array) {
  var i = 0,
      n = array.length,
      middle = Math.floor(n / 2),
      temp = null;

  for (; i < middle; i += 1) {
     temp = array[i];
     array[i] = array[n - 1 - i];
     array[n - 1 - i] = temp;
  }
}

您将阵列拆分"成两半.好吧,不是真的,您只是在上半年进行迭代.然后,使用公式n - 1 - i来找到相对于当前索引相对于中间索引对称的索引,其中i是当前索引.然后,使用临时变量交换元素. 该公式正确,因为它将交换:

You "split" the array in half. Well, not really, you just iterate over the first half. Then, you find the index which is symmetric to the current index relative to the middle, using the formula n - 1 - i, where i is the current index. Then you swap the elements using a temp variable. The formula is correct, because it will swap:

0 <-> n - 1
1 <-> n - 2

,依此类推.如果元素数为奇数,则中间位置不会受到影响.

and so on. If the number of elements is odd, the middle position will not be affected.

这篇关于反向阵列到位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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