Austin Sefton - 6 months ago 72

Javascript Question

Why won't this function

`reverseArrayInPlace`

`arr`

`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.