Austin Sefton Austin Sefton - 3 months ago 37
Javascript Question

reverse array in place

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)

Answer

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;
  }
}

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.