I am a 4th semester CS student from Germany and still don't grasp recursion, even though I already took the data structures & algorithms courses. If you did have something like a magic moment where it made sense to you, please enlighten me as I would really like to truly gain an intuition (and implement a parallelized msd-radixsort for learning-purposes because I failed to do this assignment yesterday).
To make sure your function will stop calling itself you need an exit-condition. So whenever you want to write a recursive function, simply start with a template like this:
function myFunc(list) {
// exit condition
if (list.length == 0) {
// What should the function do if the exit condition is true
return
} else {
// before recursion
console.log(list[0])
// recursion
myFunc(list.slice(1))
// after recursion
}
}
So basically you have to think about when your function aborts the recursion, what it does before the recursion (e.g. extract an element from a list), how the recursive call is different from the original call (e.g. the list got reduced by one element) and after what it does after the recursive call (e.g. push a modified element to a stack). By answering those questions you should be able to solve a whole bunch of recursive problems.Before I learned this pattern, my recursive functions were a mess. Now, they all adhere to that very template and I find it actually fun to write recursive functions as there are some problems which are a lot easier to solve with them.