svmartin
4/10/2017 - 12:53 AM

reverseArrayInPlace.js

// This is what is supplied by the author as one possible solution.
function reverseArrayInPlace(array) {
  // returns original array reversed
  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;
}

// Let's work through an example using the code from the function above, but doing it "manually."
var array = [1, 2, 3, 4, 5]; // test array to work with
// We start with an array with five elements.

// the for loop is initiated with i at 0/
var i = 0;

// We will keep iterating while i is less than 2
Math.floor(array.length / 2);

// We create and initiaite the variable 'old' with the element found at array[i], which is 1 the first time
// We do this because we need to store the value of the first element.
var old = array[i]; // => 1

// We now reassign the first element to the last element.
array[i] = array[array.length - 1 - i]; // => 5
// We assign the last element with what we stored in 'old'.
array[array.length - 1 - i] = old; // => 1

// array is currently => [5, 2, 3, 4, 1]
// Now, we increment i++
// i => 1

// We now start the second iteration and i is 1.
array[i] = array[array.length - 1 - i]; // => 4

// We assign the last element with what we stored in 'old'.
array[array.length - 1 - i] = old; // => 2

// array is currently => [5, 4, 3, 2, 1]
// Now, we increment i++
// i => 3
// We stop because i is now greater than Math.floor(array.length / 2).