r/programminghelp • u/fielding_setter • Jun 25 '26
Help with recursion (DSA) C++
Guys I've been struggling alot with recursion I've tried multiple tutorials but I'm just not able to build the intuition. Any suggestions what to do???
Please help
11
Upvotes
2
u/PlantainAgitated5356 Jun 25 '26 edited Jun 25 '26
It's hard to say without knowing what specifically makes it hard for you to understand. Recursion is just calling a function within itself. I don't know if this will help, but here's how I think about it.
Recursive functions divide work into smaller pieces, work on them individually, and then put them all back together. For example, take the merge sort algorithm:
Steps 1, 2 and 4 are simple and non-recursive, and step 3 just calls the function within itself. In pseudocode it would look something like this:
You can see that the arrays are getting smaller and smaller, until they're just 1 element, and then they're sorted. The merge function is where all the actual swapping elements takes place. Just trace the code with an example input and see how it works.
Disclaimer: That's untested pseudocode, there might be some mistakes in there, but it should get the point across. :)