I can't understand why the following code snippet leads to error. Any ideas?
Maximum call stack size exceeded
function reverseArrayInPlace(array, low, high) {
if (low == undefined) {
low = 0;
}
if (high == undefined) {
high = array.length - 1;
}
if (low >= high) {
return;
}
var temp = array[low];
array[low] = array[high];
array[high] = temp;
return reverseArrayInPlace(array, low++, high--);
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
2 Answers 2
It's because you're using post-increment and post-decrement. It increments/decrements the variable, but returns the old value, so you're passing the old value in the recursion. As a result, the recursive call is identical to the original call, and you recurse infinitely.
Pre-increment/decrement -- ++low and --high -- would work correctly. But you don't need to update the variables at all, since you never use them again. Just do normal addition/subtraction.
There's also no point in using return reverseArrayInPlace() when you make the recursive call, because the base case doesn't return anything. Just make the recursive call without putting it in a return statement.
function reverseArrayInPlace(array, low, high) {
if (low == undefined) {
low = 0;
}
if (high == undefined) {
high = array.length - 1;
}
if (low >= high) {
return;
}
var temp = array[low];
array[low] = array[high];
array[high] = temp;
reverseArrayInPlace(array, low + 1, high - 1);
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
9 Comments
return with the recursive call.return but not return someExpression, so it doesn't return anything.because you have to use ++low and --high in the recursive call. in your version the values are first passed and then modified.
function reverseArrayInPlace(array, low, high) {
if (low == undefined) {
low = 0;
}
if (high == undefined) {
high = array.length - 1;
}
if (low >= high) {
return;
}
var temp = array[low];
array[low] = array[high];
array[high] = temp;
return reverseArrayInPlace(array, ++low, --high);
}
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
1 Comment
low + 1 and high - 1.
if (low >= high)isn't being hit. You always fall through to the recursive case, which the JS engine eventually blocks because otherwise it would go on forever. Maybe that will help you debug the algorithm.console.logcalls to track what values are being passed in.