Mark Danishevsky

Tutorials: Recursion

Back to tutorials home

Recursion Navigation

It is recomended that you learn recursion before this topic.

What is recursion?

Recursion is a programming technique where a method calls itself to solve smaller versions of a problem.

A recursive method has two essential parts:

Example — Factorial (n!)

In the code above, factorial(0) returns 1 (base case), and otherwise, the method keeps calling itself with a smaller n.

All problems which can be solved with iteration (loops) can be solved with recursion. Are all problems that are solvable with recursion solvable with loops? - Stack Overflow

Recursive Searching

Binary Search (Recursive Version)

Binary Search efficiently finds a target value in a sorted array by repeatedly dividing the search interval in half. Its time complexity is O(log n). It requires that the array is sorted.

You can see an example of recursive Binary Search below:

A call to binarySearch returns the index of an element with value target in the array arr, between the indices of left and right.

The algorithm works in the following manner:

Binary Search Algorithm – Iterative and Recursive Implementation | GeeksforGeeks

Recursive Sorting

Below you can see an example of how we can use recursion to sort an array:

Merge Sort is a divide and conquer algorithm:

Java Program for Merge Sort | GeeksforGeeks

The Java program below demonstrates a simple use of recursion to implement a text-based menu. When the program runs, it displays a menu with three options, one of them being to exit. The user is prompted to enter a choice, and based on the input, the corresponding action is performed. After completing the selected action (unless the user chooses to exit), the menu() method calls itself recursively to display the menu again. This continues until the user selects the “Exit” option, at which point the recursion stops using a return statement, and the program ends. This approach illustrates how recursion can be used as an alternative to loops for repeating a task. It is a good demonstration of how you can use recursion instead of loops. Note: it is better to use loops for this application because recursion can overflow memory much faster.