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++
void print(int n)
{
if (n < 0)
return;
cout << " " << n;
print(n-1);
}
|
Java
static void print(int n)
{
if (n < 0)
return;
System.out.print(" " + n);
print(n - 1);
}
|
Python3
def display(n):
if (n < 0):
return
print(" ", n)
display(n - 1)
|
C#
static void print(int n)
{
if (n < 0)
return;
Console.Write(" " + n);
print(n - 1);
}
|
Javascript
<script>
function print(n)
{
if (n < 0)
return;
document.write( " " + n);
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++
void print(int n)
{
start:
if (n < 0)
return;
cout << " " << n;
n = n-1
goto start;
}
|
Java
public static void print(int n)
{
start:
if (n < 0)
return;
System.out.print(" "+n);
n = n - 1
goto start;
}
|
Python3
def print(n):
while n >= 0:
print(" ", n)
n = n - 1
|
C#
public static void print(int n)
{
while(n>=0)
{
if (n < 0)
return;
Console.Write(" " + n);
n = n-1;
}
}
|
Javascript
function print( n)
{
while(n>=0)
{
if (n < 0)
return;
Console.Write(" " + n);
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++
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
|
Java
static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
|
Python3
def quickSort(arr,low,high):
if(low<high):
pi=partition(arr,low,high)
quickSort(arr,low,pi-1)
quickSort(arr,pi+1,high)
|
C#
using System;
class GFG{
static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
}
|
Javascript
function quickSort( arr, low, high)
{
if (low < high)
{
let pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
|
The above function can be replaced by following after tail call elimination.
C++
void quickSort(int arr[], int low, int high)
{
start:
if (low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
low = pi+1;
high = high;
goto start;
}
}
|
Java
void quickSort(int arr[], int low, int high) {
start:
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
low = pi + 1;
high = high;
goto start;
}
}
|
Python3
def quickSort(arr, low, high):
def start():
nonlocal low, high
if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi - 1)
low = pi + 1
start()
start()
|
C#
using System;
class QuickSort {
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++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp1 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp1;
return i + 1;
}
void Sort(int[] arr, int low, int high) {
Action start = null;
start = () => {
if (low < high) {
int pi = Partition(arr, low, high);
Sort(arr, low, pi - 1);
low = pi + 1;
start();
}
};
start();
}
void PrintArray(int[] arr) {
int n = arr.Length;
for (int i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
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
function quickSort(arr, low, high) {
let start = () => {
if (low < high) {
let pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
low = pi + 1;
high = high;
start();
}
};
start();
}
|
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
Tail Call Elimination
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/C++ Code // An example of tail recursive function void print(int n) { if (n < 0) return; cout << " " << n; // The last execut
10 min read
Tail Call Optimisation in C
In C programming, Tail Call Optimization (TCO) is a technique that eliminates the need for an additional stack frame to store the data of another function by reusing the current function's stack frame. This optimization technique is only possible for tail function calls. What is Tail Call?The tail c
4 min read
Tail recursion to calculate sum of array elements.
Given an array arr, we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion so that compilers can optimize the code. If the recursive call is the last statement, the compiler can optimize it by eliminating the need to store the parent call's s
3 min read
What is a Proper Tail Call?
What is a Proper Tail Call? Proper tail calls (PTC) is a programming language feature that enables memory-efficient recursive algorithms. Tail call optimization is where you can avoid allocating a new stack frame for a function because the calling function will simply return the value it gets from t
5 min read
Tail Recursion in Python
Tail recursion is a special case of recursion where the recursive call is the last operation in the function. Therefore, the function returns the result of the recursive call directly, without performing any additional computation after the call. In some languages, tail-recursive functions can be tr
3 min read
Minimum Value X to Delete All Arrays
Given 2d array A[][] of size N*M. Your Task is to choose the minimum possible number X to perform the following operation. In one operation choose any array i from N arrays and delete the first element, if it is less than X, and increase X by 1. Keep performing this operation until the array becomes
12 min read
Gaussian Elimination to Solve Linear Equations
The Gaussian Elimination Method is a widely used technique for solving systems of linear equations. A system of linear equations involves multiple equations with unknown variables. The goal of solving such a system is to find the values of these unknowns that satisfy all the given equations simultan
15+ min read
Variation in Nim Game
Prerequisites: Sprague Grundy theorem Grundy NumbersNim is a famous game in which two players take turns removing items from distinct piles. During each turn, a player must remove one or more items from a single, non-empty pile. The winner of the game is whichever player removes the last item from t
8 min read
What is Tail Recursion
Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. For example the following function print() is tail recursive. [GFGTABS] C++ // An example of tail re
7 min read
Tail vs. Non-Tail Recursion
Tail recursion and Non-tail recursion are two types of recursive functions in computer programming. In this post we will deep dive into what are the major differences between the tail and non-tail recursion. 1) Definition:Tail recursion is defined by having the recursive call as the last operation i
3 min read