QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Last Updated :
23 Jul, 2025
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 part has 0 elements and other part has n-1 elements. For example, in below code, if we choose last element as pivot, we get worst case for sorted arrays (See this for visualization)
C++
#include <iostream>
// Function to partition the array and return the pivot index
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the pivot as the last element
int i = low - 1; // Initialize the index of the smaller element
for (int j = low; j < high; j++) {
// If the current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment the index of the smaller element
std::swap(arr[i], arr[j]); // Swap arr[i] and arr[j]
}
}
// Swap the pivot element with the element at index (i + 1)
std::swap(arr[i + 1], arr[high]);
return i + 1; // Return the pivot index
}
// Function to perform the QuickSort algorithm
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Find the pivot index such that elements smaller than the pivot
// are on the left and elements greater than the pivot are on the right
int pi = partition(arr, low, high);
// Recursively sort the elements before and after the pivot
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
std::cout << "Original array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
quickSort(arr, 0, n - 1);
std::cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
C
/* A Simple implementation of QuickSort that makes two
two recursive calls. */
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);
}
}
// See below link for complete running code
// https://www.geeksforgeeks.org/dsa/quick-sort-algorithm/
Java
// A Simple implementation of QuickSort that
// makes two recursive calls.
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 rutvik_56
Python
# Python3 program for the above approach
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 sanjoy_62
C#
// A Simple implementation of QuickSort that
// makes two recursive calls.
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 pratham76.
JavaScript
<script>
// A Simple implementation of QuickSort that
// makes two recursive calls.
function quickSort(arr , low , high)
{
if (low < high)
{
// pi is partitioning index, arr[p] is
// now at right place
var 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 umadevi9616.
</script>
Can we reduce the auxiliary space for function call stack?
We can limit the auxiliary space to O(Log n). The idea is based on tail call elimination. As seen in the previous post, we can convert the code so that it makes one recursive call. For example, in the below code, we have converted the above code to use a while loop and have reduced the number of recursive calls.
C++
/* QuickSort after tail call elimination */
#include <iostream>
using namespace std;
// A utility function to swap two elements
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
/* This function takes last element as pivot, places
the pivot element at its correct position in sorted
array, and places all smaller (smaller than pivot)
to left of pivot and all greater elements to right
of pivot */
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements 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);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
// This code code is contributed by shivhack999
C
/* QuickSort after tail call elimination using while loop */
void quickSort(int arr[], int low, int high)
{
while (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);
low = pi+1;
}
}
Java
/* QuickSort after tail call elimination using while loop */
static void quickSort(int arr[], int low, int high)
{
while (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);
low = pi+1;
}
}
Python
# QuickSort after tail call elimination using while loop '''
def quickSort(arr, low, high):
while (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)
low = pi+1
# This code is contributed by gauravrajput1
C#
/* QuickSort after tail call elimination using while loop */
static void quickSort(int []arr, int low, int high)
{
while (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);
low = pi+1;
}
}
// This code contributed by gauravrajput1
JavaScript
<script>
/* QuickSort after tail call elimination using while loop */
function quickSort(arr , low , high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
var pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
low = pi+1;
}
}
// This code is contributed by gauravrajput1
</script>
Although we have reduced number of recursive calls, the above code can still use O(n) auxiliary space in worst case. In worst case, it is possible that array is divided in a way that the first part always has n-1 elements. For example, this may happen when last element is choses as pivot and array is sorted in increasing order.
We can optimize the above code to make a recursive call only for the smaller part after partition. Below is implementation of this idea.
Further Optimization :
C++
// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
void quickSort(int arr[], int low, int high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// If left part is smaller, then recur for left
// part and handle right part iteratively
if (pi - low < high - pi)
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
// This code is contributed by code_hunt.
C
/* This QuickSort requires O(Log n) auxiliary space in
worst case. */
void quickSort(int arr[], int low, int high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// If left part is smaller, then recur for left
// part and handle right part iteratively
if (pi - low < high - pi)
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
Java
/* This QuickSort requires O(Log n) auxiliary space in
worst case. */
static void quickSort(int arr[], int low, int high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// If left part is smaller, then recur for left
// part and handle right part iteratively
if (pi - low < high - pi)
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
// This code is contributed by gauravrajput1
Python
''' This QuickSort requires O(Log n) auxiliary space in
worst case. '''
def quickSort(arr, low, high)
while (low < high):
''' pi is partitioning index, arr[p] is now
at right place '''
pi = partition(arr, low, high);
# If left part is smaller, then recur for left
# part and handle right part iteratively
if (pi - low < high - pi):
quickSort(arr, low, pi - 1);
low = pi + 1;
# Else recur for right part
else:
quickSort(arr, pi + 1, high);
high = pi - 1;
# This code is contributed by gauravrajput1
C#
/* This QuickSort requires O(Log n) auxiliary space in
worst case. */
static void quickSort(int []arr, int low, int high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// If left part is smaller, then recur for left
// part and handle right part iteratively
if (pi - low < high - pi)
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
// This code is contributed by gauravrajput1
JavaScript
<script>
/* This QuickSort requires O(Log n) auxiliary space in
worst case. */
function quickSort(arr , low , high)
{
while (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
var pi = partition(arr, low, high);
// If left part is smaller, then recur for left
// part and handle right part iteratively
if (pi - low < high - pi)
{
quickSort(arr, low, pi - 1);
low = pi + 1;
}
// Else recur for right part
else
{
quickSort(arr, pi + 1, high);
high = pi - 1;
}
}
}
// This code contributed by gauravrajput1
</script>
In the above code, if left part becomes smaller, then we make recursive call for left part. Else for the right part. In worst case (for space), when both parts are of equal sizes in all recursive calls, we use O(Log n) extra space.
Reference:
https://www.cs.nthu.edu.tw/~wkhon/algo08-tutorials/tutorial2b.pdf
This article is contributed by Dheeraj Jain.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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