Im working through this problem in a javascript book to reverse an array, and I just dont know why this code isnt working. Can someone please explain? This codes supposed to swap the values, but it does nothing to the array.
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function reverseArrayInPlace(array) {
for (let start = 0, end = array.length - 1; start < array.length, end >= 0; start++, end--) {
let x = array[start];
array[start] = array[end];
array[end] = x;
}
return array;
}
reverseArrayInPlace(nums);
console.log(nums);
3 Answers 3
You need just to check if start is smaller then end. The other check is superfluous, because before end reaches zero, the loop stops.
function reverseArrayInPlace(array) {
for (let start = 0, end = array.length - 1; start < end; start++, end--) {
let x = array[start];
array[start] = array[end];
array[end] = x;
}
return array;
}
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
reverseArrayInPlace(nums);
console.log(nums);
Comments
This code swaps each pair of elements twice: once when start < end and once when start > end. In your if statement, you want to change the break condition to start < end and not start < array.length.
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function reverseArrayInPlace(array) {
for (let start = 0, end = array.length - 1; start < end; start++, end--) {
let x = array[start];
array[start] = array[end];
array[end] = x;
}
return array;
}
reverseArrayInPlace(nums);
console.log(nums);
2 Comments
As long as the values in the array are integers, you can perform a bit-wise exclusive or (XOR) without the need a a temporary variable. You could also do this with one control variable i.e. i. The time complexity will be O(n/2).
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function reverseIntArrayInPlace(arr) {
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
arr[i] = arr[i] ^ arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = arr[i] ^ arr[arr.length - 1 - i];
arr[i] = arr[i] ^ arr[arr.length - 1 - i];
}
return arr;
}
console.log(reverseIntArrayInPlace(nums));
.as-console-wrapper { top: 0; max-height: 100% !important; }
If you want to swap other types, then you will need a temporary variable.
let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function reverseArrayInPlace(arr) {
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
const tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
return arr;
}
console.log(reverseArrayInPlace(nums));
.as-console-wrapper { top: 0; max-height: 100% !important; }
array.reverse()method does exist.