Why is quicksort N * log(N)?

tl;dr

For the super impatient, the following quicksort recursion diagram may be sufficient.

Recursion Input array partitions
Depth
1
Input array (complete)
Input array, N items, to be partitioned
Depth
2
low partition high partition
2 partitions of N/2 elements: still N elements; each to be partitioned
Depth
3
low-low pt. low-high pt. high-low pt. high-high pt.
4 partitions of N/4 elements: still N elements; each to be partitioned
Depth
4
l-l-l pt. l-l-h pt. l-h-l pt. l-h-h pt. h-l-l pt. h-l-h pt. h-h-l pt. h-h-h pt.
8 partitions of N/8 elements: still N elements; each to be partitioned
Depth
5
llll lllh llhl llhh lhll lhlh lhhl lhhh hlll hllh hlhl hlhh hhll hhlh hhhl hhhh
partitioning will continue until sorting concludes

However, even the impatient are welcome to read the rest of the article, either from the beginning, or jump straight to N * log(N) complexity, illustrated by quicksort.

Introduction

Constant, linear and quadratic complexities are easy to understand:

  • Given a collection of N elements, you go through each element once? That’s \(O(N)\). What if you just walk through half of the collection? \(N/2\), which is still linear because what matters is how the complexity grows with input size.

  • Given a collection of N elements, you walk through it, but per each element you fully process the same collection? This means you process the collection of N elements N times. That’s \(N \cdot N\), meaning \(N^2\).

  • Given a collection of n with N elements and a collection m of M elements, you walk through n and for each element you walk through m in a nested loop? That’s \(N \cdot M\) - multiplicative complexity.

  • Constant complexity is trivial - you do something once and you’re done.

But how can we build an intuition about logarithmic and \(N \cdot log(N)\) complexities?

Logarithmic complexity

Logarithms - an intuition

Every high-schooler is taught that logarithms are the “opposite” of exponentiation. Not all of us did enough work with logarithms, though, to actually internalise them. Have I? I’m not sure, I might have been lazy or might have forgotten. So let’s rebuild our intuition here.

The logarithm notation looks as follows:

\[\log_b x = y\]

b is the logarithm base, x is the log function argument, and y is the result.

The notation reads: “to which power do I need to raise b to obtain x”. This means the above is equivalent to the following:

\[b^y = x\]

Historically, logarithms were developed to simplify multiplication of large numbers by reducing it to addition, taking advantage of the following property:

\[\log_b (m*n) = \log_b m + \log_b n\]

Meaning that given logarithmic tables and some skill, one could convert a tedious multiplication into two table lookups, addition, and another table lookup in the opposite direction. The downside was some precision loss from the reliance on logarithmic tables, which could only offer a finite precision. We won’t be getting into that but I encourage anyone interested to look it up. Or ask a chatbot.

Later on, logarithms kept popping up in various fields in maths, physics, and engineering - whenever we had a result of some exponential phenomenon but we wanted to know the state of the system before said exponential behaviour took place. And since exponentiation is just a series of multiplications by the same number, it’s rather unsurprising that we encounter it and its logarithmic counterpart so often.

Real-world example

My go-to example of logarithms is the following calculation around radioactive element half-lives.

Given 10kg of an element with a half-life of 1 day, the next day there will be \(\frac{10}{2}\) kg of that element, on the second day \(\frac{10}{4}\), on the third day \(\frac{10}{8}\), etc.

Note

To anyone asking “how do we know how much of the element is left”: maybe the fission product is a gas and just flies away. Or maybe it is not radioactive and makes a poor shield, meaning that we can figure out the mass of the radioactive element from the amount of radiation.

So on day N there will be \(\frac{10}{2^N}\) kg left. Let’s say that on a given day there’s only \(\boldsymbol{\frac{10}{64}}\) kg of the element left but we don’t know which day it is. We ask ourselves - to which power 2 needs to be raised to get 64? Behold: we’ve just formulated the following logarithm:

\[\log_2 64\]

You may remember that \(2^6 = 64\) or use a calculator:

In [1]: import math

In [2]: math.log(64, 2)  # the base comes second and cannot be a kwarg
Out[2]: 6.0

Our answer is: it is the sixth day.

Logarithms in computing

Where do we encounter similar exponentiation patterns in computing? Easy example - in tree data structures.

A binary tree can hold 1 element in its root node (level 0), 2 elements below (level 1), 4 elements on level 2, 8 elements on level 3, etc. Counting levels from zero, level N holds \(\boldsymbol 2^N\) elements. See:

  • \(2^0\) = 1

  • \(2^1\) = 2

  • \(2^2\) = 4

  • \(2^3\) = 8

  • …

Note

\(B^0\) is 1 for any B apart from 0, for which it isn’t defined.

Why is \(B^0\) always 1 for any \(B \neq 0\)? For consistency in various properties, for example this one:

\[ \begin{align}\begin{aligned}\underbrace{B \cdot B \dotsm B}_{\text{M times}} \cdot \underbrace{B \cdot B \dotsm B}_{\text{N times}} = \underbrace{B \cdot B \dotsm B}_{\text{M + N times}}\\\text{or otherwise:} \quad B^M \cdot B^N = B^{(M+N)}\end{aligned}\end{align} \]

let’s say that \(N = 0\)

\[\begin{split}B^M \cdot B^0 &= B^{(M+0)} \\ B^M \cdot B^0 &= B^M &&\big|\; \div{B^M} \quad (\text{assuming} \; B^M \neq 0) \\ B^0 &= \frac{B^M}{B^M} \\ B^0 &= 1\end{split}\]

Since we had to divide by \(B^M\), we had to exclude \(B^M = 0\). A power like \(B^M\) can only be zero if the base B is zero, therefore we’re actually only excluding \(B = 0\). This is compatible with the initial remark that B cannot be zero.

To simplify our maths, let’s say that in our tree only leaf elements can store data. It means that in order to store K elements, the final level must consist of at least K elements. Not all K’s will be powers of 2 but for K’s that are, the leaf nodes are exactly \(log_2 K\) levels below the root (counting the root as level 0). This means \(log_2 K\) downward steps to travel from the root, through all intermediate nodes, to the leaf node holding the value.

For K’s that aren’t a power of 2, we either have to:

  • find the nearest power of 2 greater than K, which we’ll call P, and take the binary logarithm of that: \(log_2(P) \: \text{where} \; P>K \text{ and } P = 2^k\)

  • exploit the fact that the log function is defined for arguments other than integer powers of its base. We’ll need to round the result up to the nearest integer, because a tree doesn’t have fractional levels: \(\lceil log_2(K) \rceil\)

The \(\boldsymbol{log(N)}\) complexity is encountered when a problem is recursively divided into nested sub-problems forming a real tree data structure or a conceptual tree of decisions, with each level shrinking the problem by a constant factor. A notable example of a tree of decisions could be all possible traversals when performing a binary search.

In complexity analysis we can for the most part ignore the logarithm base, which in computing is typically some constant like 2, 8, or 32. What decides on the base? In the case of a tree, the tree’s branching factor decides, meaning the number of children of each of its nodes. A quadtree lookup has the complexity of \(log_4(K)\), an octree - \(log_8(K)\), etc.

Trees that store data in all nodes

What about trees that store their data in all nodes, not just leaf nodes? They do not escape the logarithmic complexity. For a binary tree, level N+1 can store one element more than all levels up to N (inclusive) can store together. So we’re talking roughly twice the data capacity of a tree with uninhabited non-leaf nodes. “Twice” is a constant multiplier and we generally don’t care about constant multipliers in complexity analysis.

N * log(N) complexity, illustrated by quicksort

This one gets more complicated. With some hand-waving, it can be explained as doing a linear operation a logarithmic number of times… Is that helpful? No? Let’s then talk about what quicksort actually does.

Quicksort overview

Quicksort is a sorting algorithm that recursively partitions its input array into “lower” and “higher” sub-sequences, based on a chosen pivot value. The “lower” partition contains values less than or equal to the pivot, while the “higher” part - values greater than the pivot.

The pivot must be chosen so that the “lower” and “higher” fractions remain of roughly equal size. Bad pivot selection degrades the complexity guarantee but this phenomenon isn’t what this article is about.

After partitioning, the same algorithm is called recursively on:

  • left-recursion on the “lower” partition (detail: excluding its last element, which is the pivot value, otherwise the left-recursion will not terminate)

  • right-recursion on the “higher” partition

Also, remember:

  • Partitions of lengths 0 or 1 are automatically sorted and will not be recursed into.

  • There are also other partitioning schemes, however they all have the same linear complexity with different constant factors (multipliers). We’ve only described the most trivial one (Lomuto).

Quicksort analysis

The complexity of pivot selection is typically constant time and therefore not considered. The crux of the work done by quicksort lies in the partitioning operation.

Work per recursion level

The partitioning operation has a linear complexity, since it is a simple loop traversing its input array once.

The previous section included a detail stating that the left-recursive call is made on the subarray excluding the last element of the left partition. We’ll ignore it [1] and assume that each partitioning step produces two partitions half the size of the original.

With these assumptions, partition size will keep decreasing geometrically, while the number of partitioning operations will be increasing geometrically.

level

partition length

partitions

0

N

1

1

N / 2

2

2

N / 4

4

3

N / 8

8

Once we chart the partitioning operations by recursion level, we see that within each level, the sum of the lengths of partitioned sequences adds up to the length of the initial array. This should convince us that the complexity at each recursion level adds up to \(\boldsymbol{O(N)}\).

Recursion Input array partitions
Depth
1
Input array (complete)
Input array, N items, to be partitioned
Depth
2
low partition high partition
2 partitions of N/2 elements: still N elements; each to be partitioned
Depth
3
low-low pt. low-high pt. high-low pt. high-high pt.
4 partitions of N/4 elements: still N elements; each to be partitioned
Depth
4
l-l-l pt. l-l-h pt. l-h-l pt. l-h-h pt. h-l-l pt. h-l-h pt. h-h-l pt. h-h-h pt.
8 partitions of N/8 elements: still N elements; each to be partitioned
Depth
5
llll lllh llhl llhh lhll lhlh lhhl lhhh hlll hllh hlhl hlhh hhll hhlh hhhl hhhh
partitioning will continue until sorting concludes

Each of the levels in the table represents one level of recursion depth as well as the partitions operated on. But how many recursion levels are there?

Number of recursion levels

We stated before that each subsequent recursion level will have its partition size divided by 2.

Formally speaking, this means that at level K, the length will be \(N/2^K\). Since the algorithm terminates when partition length reaches 1 or 0, we can express the total number of recursions, K, as:

\[\begin{split}\frac{N}{2^K} &= 1 \\ \frac{N}{2^K} &= \frac{N}{N} \\ 2^K &= N \\ log_2(N) &= K\end{split}\]

Therefore the total number of recursions will grow logarithmically with the length of the input sequence. There will be \(\mathbf{log_2(N)}\) recursion levels.

Note

Partition length is discrete but the expression \(\frac{N}{2^K}\) is continuous for K>0, where for ever increasing K, it keeps approaching 0, never reaching it. We hand-wave the mapping between continuous and discrete domains.

Final complexity

We have \(log_2(N)\) levels of \(O(N)\) work! Adding up the work over all the levels gives \(O(N \cdot log_2(N))\), which is the final complexity of quicksort with optimal partitioning.