![]() |
Recursion is a programming technique in which a function calls itself directly or indirectly. Using a recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Recursion is a technique in which we reduce the length of code and make it easy to read and write. A recursive function solves a problem by calling its own function and also calling for the smaller subproblem. Recursion is a powerful technique that has many applications in the field of programming. Below are a few common applications of recursion that we frequently use:
Let’s deep dive into each application: Tree traversalThe traversal of trees is very interesting, we can traverse trees in different ways. Recursion is also a very common way to traverse and manipulate tree structures. Example: In this example, we will show all three traversal(inorder, postorder and preorder) using recursion. Javascript
Output
Inorder traversal of binary tree is 4 2 5 1 3 Preorder traversal of binary tree is 1 2 4 5 3 Postorder traversal of binary tree is 4 5 2 3 1 Sorting algorithmA Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. There are various types of sorting. We are going to see insertion sort using recursion.Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Example: In this example, we will see the insertion sort using recursion. Javascript
Output
1 3 5 6 8 9 Divide-and-conquer algorithmsDivide and Conquer is an algorithmic paradigm in which the problem is solved using the Divide, Conquer, and Combine strategy. A typical Divide and Conquer algorithm solves a problem using following three steps:
A classic example of Divide and Conquer is Merge Sort demonstrated below. In Merge Sort, we divide array into two halves, sort the two halves recursively, and then merge the sorted halves. Example: In this example, we will show the merge sorting using recursion: Javascript
Output
Sorted array is 3 4 5 6 7 9 Sieve of EratosthenesThis algorithm is most optimised solution for finding the prime number. Example: In this example, we will show the Sieve of Eratosthenes. Javascript
Output
true false Fibonacci NumbersIn mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation: F_{n} = F_{n-1} + F_{n-2} with seed values and F_0 = 0 and F_1 = 1 . The Nth Fibonacci Number can be found using the recurrence relation shown above:
Example: In this example, we will find the nth Fibonacci Number using Recursion. Javascript
Output
6th Fibonacci Number: 8 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |