I am working through the exercises in Eloquent JavaScript by Marijn Haverbeke and am working on the following problem:
"Write a function reverseArrayInPlace that modifies the array given as an argument in order to reverse its elements. Do not use the standard
reverse
method"
The solution given is as follows:
function reverseArrayInPlace(array) {
for (var i = 0; i < Math.floor(array.length / 2); i++) {
var old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
The test case given is as follows:
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// → [5, 4, 3, 2, 1]
I understand that it is using the midpoint of the array as a rotation point, but can someone please give me a step by step explanation?