QuickSort Tail Call Optimization (Reducing worst case space to Log n )
Last Updated :
23 Apr, 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/quick-sort/
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:
http://www.cs.nthu.edu.tw/~wkhon/algo08-tutorials/tutorial2b.pdf
This article is contributed by Dheeraj Jain.
Similar Reads
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. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Time and Space Complexity Analysis of Quick Sort The time complexity of Quick Sort is O(n log n) on average case, but can become O(n^2) in the worst-case. The space complexity of Quick Sort in the best case is O(log n), while in the worst-case scenario, it becomes O(n) due to unbalanced partitioning causing a skewed recursion tree that requires a
4 min read
Application and uses of Quicksort Quicksort: Quick sort is a Divide Conquer algorithm and the fastest sorting algorithm. In quick sort, it creates two empty arrays to hold elements less than the pivot element and the element greater than the pivot element and then recursively sort the sub-arrays. There are many versions of Quicksort
2 min read
QuickSort using different languages
Iterative QuickSort
Different implementations of QuickSort
QuickSort using Random PivotingIn this article, we will discuss how to implement QuickSort using random pivoting. In QuickSort we first partition the array in place such that all elements to the left of the pivot element are smaller, while all elements to the right of the pivot are greater than the pivot. Then we recursively call
15+ min read
QuickSort Tail Call Optimization (Reducing worst case space to Log n )Prerequisite : Tail Call EliminationIn 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 selecte
11 min read
Implement Quicksort with first element as pivotQuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the pivot. There are many different versions of quickSort that pick the pivot in different ways. Always pick the first element as a pivot.Always pick the last element as a pivot.Pick a
13 min read
Advanced Quick Sort (Hybrid Algorithm)Prerequisites: Insertion Sort, Quick Sort, Selection SortIn this article, a Hybrid algorithm with the combination of quick sort and insertion sort is implemented. As the name suggests, the Hybrid algorithm combines more than one algorithm. Why Hybrid algorithm: Quicksort algorithm is efficient if th
9 min read
Quick Sort using Multi-threadingQuickSort is a popular sorting technique based on divide and conquer algorithm. In this technique, an element is chosen as a pivot and the array is partitioned around it. The target of partition is, given an array and an element x of the array as a pivot, put x at its correct position in a sorted ar
9 min read
Stable QuickSortA sorting algorithm is said to be stable if it maintains the relative order of records in the case of equality of keys.Input : (1, 5), (3, 2) (1, 2) (5, 4) (6, 4) We need to sort key-value pairs in the increasing order of keys of first digit There are two possible solution for the two pairs where th
9 min read
Dual pivot QuicksortAs we know, the single pivot quick sort takes a pivot from one of the ends of the array and partitioning the array, so that all elements are left to the pivot are less than or equal to the pivot, and all elements that are right to the pivot are greater than the pivot.The idea of dual pivot quick sor
10 min read
3-Way QuickSort (Dutch National Flag)In simple QuickSort algorithm, we select an element as pivot, partition the array around a pivot and recur for subarrays on the left and right of the pivot. Consider an array which has many redundant elements. For example, {1, 4, 2, 4, 2, 4, 1, 2, 4, 1, 2, 2, 2, 2, 4, 1, 4, 4, 4}. If 4 is picked as
15+ min read
Visualization of QuickSort
Partitions in QuickSort
Some problems on QuickSort
Is Quick Sort Algorithm Adaptive or not Adaptive sorting algorithms are designed to take advantage of existing order in the input data. This means, if the array is already sorted or partially sorted, an adaptive algorithm will recognize that and sort the array faster than it would for a completely random array.Quick Sort is not an adaptiv
6 min read