We have discussed (in tail recursion) that a recursive function is tail recursive if the recursive call is the last thing executed by the function.
C++
// An example of tail recursive function
void print(int n)
{
if (n < 0)
return;
cout << " " << n;
// The last executed statement is recursive call
print(n-1);
}
Java
// An example of tail recursive function
static void print(int n)
{
if (n < 0)
return;
System.out.print(" " + n);
// The last executed statement
// is recursive call
print(n - 1);
}
// This code is contributed by rutvik_56
Python
# An example of tail recursive function
def display(n):
if (n < 0):
return
print(" ", n)
# The last executed statement is recursive call
display(n - 1)
# This code is contributed by sanjoy_62
C#
// An example of tail recursive function
static void print(int n)
{
if (n < 0)
return;
Console.Write(" " + n);
// The last executed statement
// is recursive call
print(n - 1);
}
// This code is contributed by pratham76
JavaScript
<script>
// An example of tail recursive function
function print(n)
{
if (n < 0)
return;
document.write( " " + n);
// The last executed statement is recursive call
print(n-1);
}
</script>
We also discussed that a tail-recursive is better than a non-tail recursive as tail-recursion can be optimized by modern compilers. Modern compiler basically does tail call elimination to optimize the tail-recursive code.
If we take a closer look at the above function, we can remove the last call with goto. Below are examples of tail call elimination.
C++
// Above code after tail call elimination
void print(int n)
{
start:
if (n < 0)
return;
cout << " " << n;
// Update parameters of recursive call
// and replace recursive call with goto
n = n-1
goto start;
}
Java
// Java code after tail call elimination
public static void print(int n)
{
start:
if (n < 0)
return;
System.out.print(" "+n);
// Update parameters of recursive call
// and replace recursive call with goto
n = n - 1
goto start;
}
// This code is contributed by ishankhandelwals.
Python
# Python code after tail call elimination
def print(n):
while n >= 0:
print(" ", n)
# Update parameters of recursive call
# and replace recursive call with goto
n = n - 1
# This code is contributed by ishankhandelwals.
C#
// Above code after tail call elimination
public static void print(int n)
{
while(n>=0)
{
if (n < 0)
return;
Console.Write(" " + n);
// Update parameters of recursive call
// and replace recursive call with goto
n = n-1;
}
}
// The code is contributed by Arushi Jindal.
JavaScript
// Above code after tail call elimination
function print( n)
{
while(n>=0)
{
if (n < 0)
return;
Console.Write(" " + n);
// Update parameters of recursive call
// and replace recursive call with goto
n = n-1;
}
}
QuickSort : One more example
QuickSort is also tail recursive (Note that MergeSort is not tail recursive, this is also one of the reasons why QuickSort performs better)
C++
/* Tail recursive function for QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
Java
/* Java program to implement the above approach
Tail recursive function for quick sort
arr[] --> to get the elements
low --> starting index
high --> ending index
*/
static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
/* pi is partitioning index,after the call
to partition function the arr[p] will be
at its correct index*/
int pi = partition(arr, low, high);
// Sort elements before and after
// the partition separately
// thus whole array will get sorted eventually
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// This code was contributed by Abhijeet Kumar
Python
# Python program to implement
# the above approach
# Tail recursive function for QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index */
def quickSort(arr,low,high):
if(low<high):
# pi is partitioning index, arr[p] is now
# at right place
pi=partition(arr,low,high)
# Separately sort elements before
# partition and after partition
quickSort(arr,low,pi-1)
quickSort(arr,pi+1,high)
# This code is contributed by Pushpesh Raj.
C#
// C# program to implement
// the above approach
using System;
class GFG{
/* Tail recursive function for QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
}
// This code is contributed by code_hunt.
JavaScript
/* Tail recursive function for QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
function quickSort( arr, low, high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
let pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// This code was contributed by poojaagrawal2.
The above function can be replaced by following after tail call elimination.
C++
/* QuickSort after tail call elimination
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
start:
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
// Update parameters of recursive call
// and replace recursive call with goto
low = pi+1;
high = high;
goto start;
}
}
Java
// QuickSort after tail call elimination
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
void quickSort(int arr[], int low, int high) {
start:
if (low < high) {
// pi is partitioning index, arr[p] is now
// at right place
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
// Update parameters of recursive call
// and replace recursive call with goto
low = pi + 1;
high = high;
goto start;
}
}
// This code is contributed Aman Kumar.
Python
def quickSort(arr, low, high):
def start():
nonlocal low, high
if low < high:
# pi is the partitioning index, arr[p] is now at the right place
pi = partition(arr, low, high)
# Separately sort elements before partition and after partition
quickSort(arr, low, pi - 1)
# Update parameters of the recursive call
# and replace recursive call with a function call
low = pi + 1
start()
start()
C#
using System;
class QuickSort {
// Function to perform the partitioning of the array
int Partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
// Swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Swap arr[i+1] and arr[high] (or pivot)
int temp1 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp1;
return i + 1;
}
// Main sorting function with a different name
void Sort(int[] arr, int low, int high) {
Action start = null;
start = () => {
if (low < high) {
int pi = Partition(arr, low, high);
// Separately sort elements before partition
Sort(arr, low, pi - 1);
// Replace the recursive call with the start function call
low = pi + 1;
start();
}
};
start();
}
// Function to print the sorted array
void PrintArray(int[] arr) {
int n = arr.Length;
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
// Driver code
static void Main() {
QuickSort quickSort = new QuickSort();
int[] arr = { 64, 25, 12, 22, 11 };
int n = arr.Length;
Console.WriteLine("Unsorted array:");
quickSort.PrintArray(arr);
quickSort.Sort(arr, 0, n - 1);
Console.WriteLine("Sorted array:");
quickSort.PrintArray(arr);
}
}
JavaScript
// QuickSort after tail call elimination
// arr[] --> Array to be sorted,
// low --> Starting index,
// high --> Ending index
function quickSort(arr, low, high) {
let start = () => {
if (low < high) {
// pi is partitioning index, arr[p] is now at right place
let pi = partition(arr, low, high);
// Separately sort elements before partition and after partition
quickSort(arr, low, pi - 1);
// Update parameters of recursive call
// and replace recursive call with goto
low = pi + 1;
high = high;
start();
}
};
start();
}
// The code is contributed by Arushi Goel.
Therefore job for compilers is to identify tail recursion, add a label at the beginning and update parameter(s) at the end followed by adding the last goto statement.
Function stack frame management in Tail Call Elimination :
Recursion uses a stack to keep track of function calls. With every function call, a new frame is pushed onto the stack which contains local variables and data of that call. Let's say one stack frame requires O(1) i.e, constant memory space, then for N recursive call memory required would be O(N).
Tail call elimination reduces the space complexity of recursion from O(N) to O(1). As function call is eliminated, no new stack frames are created and the function is executed in constant memory space.
It is possible for the function to execute in constant memory space because, in tail recursive function, there are no statements after call statement so preserving state and frame of parent function is not required. Child function is called and finishes immediately, it doesn't have to return control back to the parent function.
As no computation is performed on the returned value and no statements are left for execution, the current frame can be modified as per the requirements of the current function call. So there is no need to preserve stack frames of previous function calls and function executes in constant memory space. This makes tail recursion faster and memory-friendly.
Next Article:
QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem