The Wayback Machine - https://web.archive.org/web/20241011123101/https://www.geeksforgeeks.org/tail-call-elimination/
Open In App

Tail Call Elimination

Last Updated : 03 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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


Python3




# 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.


Python3




# 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


Python3




# 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;
    }
}
// See below link for complete running code


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.


Python3




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

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 in the function before returningfunction factorial
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 the called function. The most common use is tail-re
5 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 call is the type of function call where another fun
4 min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Prerequisite : Tail Call Elimination In QuickSort, partition function is in-place, but we need extra space for recursive function calls. A simple implementation of QuickSort makes two calls to itself and in worst case requires O(n) space on function call stack. The worst case happens when the selected pivot always divides the array such that one pa
12 min read
Gaussian Elimination to Solve Linear Equations
The article focuses on using an algorithm for solving a system of linear equations. We will deal with the matrix of coefficients. Gaussian Elimination does not work on singular matrices (they lead to division by zero). Input: For N unknowns, input is an augmented matrix of size N x (N+1). One extra column is for Right Hand Side (RHS) mat[N][N+1] =
15+ min read
Program for Gauss-Jordan Elimination Method
Prerequisite : Gaussian Elimination to Solve Linear Equations Introduction : The Gauss-Jordan method, also known as Gauss-Jordan elimination method is used to solve a system of linear equations and is a modified version of Gauss Elimination Method. It is similar and simpler than Gauss Elimination Method as we have to perform 2 different process in
13 min read
Difference between Gauss Elimination Method and Gauss Jordan Method | Numerical Method
Gauss Elimination MethodGauss Elimination Method is one of the most widely used methods. This method is a systematic process of eliminating unknowns from the linear equations. This method is divided into two linear equations: Triangularization MethodBack Substitution MethodSteps Of the Gauss Elimination MethodConsider a system of equations: a11X+a1
4 min read
Sorted insert in a doubly linked list with head and tail pointers
A Doubly linked list is a linked list that consists of a set of sequentially linked records called nodes. Each node contains two fields that are references to the previous and to the next node in the sequence of nodes. The task is to create a doubly linked list by inserting nodes such that list remains in ascending order on printing from left to ri
10 min read
Tail recursion to calculate sum of array elements.
Given an array A[], we need to find the sum of its elements using Tail Recursion Method. We generally want to achieve tail recursion (a recursive function where recursive call is the last thing that function does) so that compilers can optimize the code. Basically, if recursive call is the last statement, the compiler does not need to save the stat
3 min read
Tail Recursion in Python Without Introspection
These are the special type of recursive functions, where the last statement executed inside the function is the call to the function itself. Advantages of implementing Tail Recursive functionIn this concept, the compiler doesn't need to save the stack frame of the function after the tail-recursive call is executed.It uses less memory as compared to
4 min read
Why is Tail Recursion optimization faster than normal Recursion?
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. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 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 C++ function print() is tail recursive. C/C++ Code // An example of tail recursive function void print(int n) { if (n < 0
8 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the function. Writing a tail recursion is little tric
4 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 transformed into iterative loops to avoid growing th
3 min read
How much Stack size required for BIOS interrupt call?
Stack: It is a linear data structure that follows the LIFO( Last In First Out ) order for performing the operations. BIOS: It provides a set of instructions and is responsible for booting the computer. The BIOS performs all the tests needed at startup time.Stack size required for bios interrupt calls?1) For No interrupts generated in task Formula F
2 min read
How to show Erlang call stack?
Erlang is a programming language that is well-suited for concurrent and distributed systems. One useful feature of Erlang is the ability to inspect the call stack, which is a record of the sequence of function calls that have led to the current point in the program's execution. This can be helpful for debugging purposes, or for gaining a better und
2 min read
How to Pass a String to a Function using Call by Reference?
Passing a string by reference in various programming languages involves using specific mechanisms or constructs to allow the function to modify the original string directly, rather than working with a copy. Here, I'll explain how to achieve this in C++, C#, Python, and JavaScript. Table of Content How to Pass a String to a Function using Call by Re
4 min read
How to pass a String into a function using call by value?
In various programming languages, strings are typically passed by value, which means that the function receives a copy of the original string, and any modifications made within the function do not affect the original string. Here are the steps and functions involved in passing a string by value in C++, C#, Python, JavaScript, and Java: Table of Con
3 min read
Function Call Stack in C
A function in C is a set of code that performs a specific task and can be used whenever needed just by calling it. But how the function call works and how the data of the function is stored in the memory is an area of interest for a better understanding of the concepts such as recursion. What is a Call Stack in C?A call stack in C is the stack that
4 min read
Linked List Data Structure
A 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. What is a Linked List? A linked list is a linear data structure that consists of a series of nodes connected
4 min read
Sorting Algorithms
A 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. For Example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character wit
6 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. In this tutorial, we will explore the most commonly used data structures, including arrays, linke
10 min read
Learn Data Structures and Algorithms | DSA Tutorial
Data Structures and Algorithms (DSA) refer to the study of methods for organizing and storing data and the design of procedures (algorithms) for solving problems, which operate on these data structures. DSA is one of the most important skills that every computer science student must have. It is often seen that people with good knowledge of these te
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the first pass, the maximum element goes to end (its cor
8 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element and swap it with the first element. This way we get
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data St
15+ min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorithm with IllustrationIllustration of QuickSort Algor
13 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort is to divide the array into two halves, sort each h
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, you pick a card from the unsorted group and p
10 min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
Practice Tags :