JavaScript recursion, reversing array -


i can't understand why following code snippet leads error. 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);

it's because you're using post-increment , post-decrement. increments/decrements variable, returns old value, you're passing old value in recursion. result, recursive call identical original call, , recurse infinitely.

pre-increment/decrement -- ++low , --high -- work correctly. don't need update variables @ all, since never use them again. normal addition/subtraction.

there's no point in using return reversearrayinplace() when make recursive call, because base case doesn't return anything. make recursive call without putting in 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);


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -