Write an iterative version of the recursive Quicksort algorithm.

In the previous post, we have discussed the recursive implementation of the Quicksort algorithm. We have seen that the Quicksort recursion stack can be optimized using tail recursion to minimize the recursive depth. Tail recursion makes sure that at most O(log(n)) space is used by recursing first into the smaller side of the partition of size n, then using a tail call to recur into the other. Tail recursion should be recognized by the compiler and optimized to its iterative counterpart.

We have also talked about another recursive stack space optimization. The idea was that when the total number of elements in the subarray is below some threshold k (perhaps ten elements), switch to a non-recursive sorting algorithm such as insertion sort or stop processing the subarray and later perform insertion sort on it (in O(k.n) time), as each element will be at most k positions away from its final sorted position.

But despite these performance boosts, the algorithm remains recursive. How can we convert the algorithm into an iterative one? This post discusses its iterative implementation.

 
Instead of using recursion, the idea is to use a stack to store subarray’s starting and ending index for later processing. Note that the partitioning logic would remain the same.

Practice this algorithm

The iterative Quicksort implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

-6 -3 1 2 3 5 6 8 9

Java


Download  Run Code

Output:

[-6, -3, 1, 2, 3, 5, 6, 8, 9]

Python


Download  Run Code

Output:

[-6, -3, 1, 2, 3, 5, 6, 8, 9]

Exercise: Modify above code to print in descending order.