AlgoViz

O(n log n) linearithmic time

easy 16 min

O(n log n) is linear work repeated a logarithmic number of times: n work on each of log n levels.

Video lesson · Chapter 1 of 5

Put eight maps in catalogue order

0:00 / 4:17

O(n log n) linearithmic time

1:23Reel

Read caption

Riff counts writes in three rounds of bottom-up merge sort on eight tickets. All the tickets, once per round.

How it works

Step through the idea, or press Play.

Step 1 of 3

Split in half. Divide the input into halves again and again; that makes about log₂ n levels

Understand it

Start here

What O(n log n) means

An algorithm is O(n log n), or linearithmic, when it does a linear amount of work a logarithmic number of times. The usual shape: split the input in half until the pieces are trivial, which takes about log⁡2n\log_2 n levels, and touch every item once per level. It is the cost of sorting done well.

  • n work per level

    Every level of the recursion handles all nn items once, merging or partitioning.

  • log n levels

    Halving nn down to pieces of size 1 takes ⌈log⁡2n⌉\lceil \log_2 n \rceil levels.

  • The sorting sweet spot

    No comparison sort can beat it, and it is far closer to O(n)O(n) than to O(n2)O(n^2).

The one-line formula

n⏟work per level×log⁡2n⏟levels=nlog⁡2n\underbrace{n}_{\text{work per level}} \times \underbrace{\log_2 n}_{\text{levels}} = n \log_2 n
For n=1,024n = 1{,}024 that is 1,024×10≈10,0001{,}024 \times 10 \approx 10{,}000 steps. A quadratic algorithm would need about a million.

The picture

Why n × log n

The recursion tree, level by level

The pieces get smaller but more numerous. Their sizes always add up to nn, so every level costs the same.

Merge sort on 16 items

LevelPiecesSize of eachWork on the level
011616
12816
24416
38216
4161base case
Four merge levels of 16 work each: 16×log⁡216=6416 \times \log_2 16 = 64.

The math

The divide and conquer recurrence

Merge sort splits the problem into two halves, solves each recursively, and spends O(n)O(n) combining them. Written as a recurrence and unrolled, the cncn term appears once per level.

Unrolling T(n) = 2T(n/2) + cn

T(n)=2T(n/2)+cn=4T(n/4)+2cn=8T(n/8)+3cn=2k T(n/2k)+k cn=n T(1)+cnlog⁡2n(2k=n)\begin{aligned} T(n) &= 2T(n/2) + cn \\ &= 4T(n/4) + 2cn \\ &= 8T(n/8) + 3cn \\ &= 2^k\,T(n/2^k) + k\,cn \\ &= n\,T(1) + cn\log_2 n \quad (2^k = n) \end{aligned}
After k=log⁡2nk = \log_2 n levels the pieces have size 1. The result is O(nlog⁡n)O(n \log n).

The master theorem view

T(n)=a T(n/b)+O(nd),a=bd  ⇒  T(n)=O(ndlog⁡n)T(n) = a\,T(n/b) + O(n^d), \quad a = b^d \;\Rightarrow\; T(n) = O(n^d \log n)
Merge sort has a=2a = 2 subproblems of size n/b=n/2n/b = n/2 and O(n1)O(n^1) combine work. Since 2=212 = 2^1, the answer is O(nlog⁡n)O(n \log n).

Example 1

Merge sort: always n log n

Splitting and merging [38, 27, 43, 3, 9, 82, 10]

Three levels of splitting (⌈log⁡27⌉=3\lceil \log_2 7 \rceil = 3), then merges back up. This run makes 14 comparisons, under the 3×7=213 \times 7 = 21 bound.
Python
def merge_sort(arr):    if len(arr) <= 1:               # base case: already sorted        return arr    mid = len(arr) // 2    left = merge_sort(arr[:mid])    # T(n/2)    right = merge_sort(arr[mid:])   # T(n/2)    return merge(left, right)       # O(n)def merge(left, right):    result = []    i = j = 0    while i < len(left) and j < len(right):        if left[i] <= right[j]:     # <= keeps equal items in order (stable)            result.append(left[i])            i += 1        else:            result.append(right[j])            j += 1    result.extend(left[i:])         # copy whatever is left over    result.extend(right[j:])    return resultprint(merge_sort([38, 27, 43, 3, 9, 82, 10]))   # [3, 9, 10, 27, 38, 43, 82]
The merge is the O(n) part: one pass, always taking the smaller front item. This slicing version puts the extra cell on the right (3 | 4), so it splits a little differently from the diagram, but the levels and the cost are the same.
Edit and run it in your browser

Strengths

  • O(nlog⁡n)O(n \log n) in the best, average and worst case.
  • Stable: equal items keep their original order.
  • Great for linked lists and for data too big for memory (external sorting).

Costs

  • Needs an O(n)O(n) buffer for merging.
  • Does the full work even on input that is already sorted.
  • More copying than quick sort, so often slower on arrays in practice.

Example 2

Quick sort: n log n on average

One partition step

Partitioning is one O(n)O(n) scan. How good the pivot is decides how many levels there are.

Good pivots against bad pivots

T(n)=2T(n/2)+O(n)⏟balanced splits=O(nlog⁡n)T(n)=T(n−1)+O(n)⏟pivot is the min or max=O(n2)\underbrace{T(n) = 2T(n/2) + O(n)}_{\text{balanced splits}} = O(n \log n) \qquad \underbrace{T(n) = T(n-1) + O(n)}_{\text{pivot is the min or max}} = O(n^2)
With a pivot that always lands at an end, the levels shrink by one item instead of by half: n+(n−1)+⋯+1=n(n+1)2n + (n-1) + \dots + 1 = \frac{n(n+1)}{2}.

Example 3

Heap sort: n log n in place

Heap sort in four moves
  1. 1Build a max heapO(n), sift down from the last parent
  2. 2Swap root and lastthe max reaches its final slot
  3. 3Shrink the heapthe sorted tail grows by one
  4. 4Sift the root downO(log n), one path to a leaf
Repeat: back to Build a max heap

Repeat the last three moves $n - 1$ times.

Adding up heap sort

O(n)⏟build heap+(n−1)⋅O(log⁡n)⏟extractions=O(nlog⁡n)\underbrace{O(n)}_{\text{build heap}} + \underbrace{(n-1) \cdot O(\log n)}_{\text{extractions}} = O(n \log n)
Each extraction walks one root-to-leaf path in a tree of height ⌊log⁡2n⌋\lfloor \log_2 n \rfloor.

Head to head

The O(n log n) sorts compared

AlgorithmBestAverageWorstExtra spaceStable
Merge sortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)yes
Quick sortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)O(log⁡n)O(\log n) stackno
Heap sortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(1)O(1)no
TimsortO(n)O(n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n)O(n)yes
Bubble sortO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)O(1)O(1)yes
Bubble sort is here for contrast: nested loops over adjacent pairs make it quadratic.

Which one to reach for

  • Merge sort

    Always O(nlog⁡n)O(n \log n) and stable. Best for linked lists and external sorting.

  • Quick sort

    Average O(nlog⁡n)O(n \log n), in place, fastest in practice. Use random pivots.

  • Heap sort

    Always O(nlog⁡n)O(n \log n) with O(1)O(1) memory. Same heap powers priority queues.

  • Your language's sort

    Python's sorted() is Timsort, a merge and insertion sort hybrid. Use it.

Scale

How n log n grows

nO(n)O(n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)
101033100
10010066410,000
1,0001,0009,9661,000,000
10,00010,000132,877100,000,000
1,000,0001,000,000about 20 million101210^{12}
O(nlog⁡n)O(n \log n) is much closer to O(n)O(n) than to O(n2)O(n^2): only about 20 times linear at a million.

Predicting a running time

106log⁡2106103log⁡2103≈106⋅20103⋅10=2000⇒10 ms×2000=20 s\frac{10^6 \log_2 10^6}{10^3 \log_2 10^3} \approx \frac{10^6 \cdot 20}{10^3 \cdot 10} = 2000 \quad\Rightarrow\quad 10\text{ ms} \times 2000 = 20\text{ s}
If sorting 1,000 items takes 10 ms, a million take about 20 seconds. A quadratic sort would grow a million times, to almost 3 hours.

The limit

Why comparison sorts cannot beat n log n

Decision tree for sorting a, b, c

Any comparison sort is a tree of yes or no questions. It needs one leaf per ordering, 3!=63! = 6 here, so some input needs 3 comparisons.

The lower bound

2h≥n!  ⇒  h≥log⁡2n!≈nlog⁡2n−1.44 n  ⇒  Ω(nlog⁡n)2^h \ge n! \;\Rightarrow\; h \ge \log_2 n! \approx n \log_2 n - 1.44\,n \;\Rightarrow\; \Omega(n \log n)
A binary tree of height hh has at most 2h2^h leaves. By Stirling's formula log⁡2n!\log_2 n! grows like nlog⁡2nn \log_2 n. For n=7n = 7: log⁡25040≈12.3\log_2 5040 \approx 12.3, so every comparison sort needs at least 13 comparisons on some input.

Pattern spotting

Spotting O(n log n) in code

Code shapeWhat it isCost
sorted(arr) or arr.sort()Built-in sort (Timsort)O(nlog⁡n)O(n \log n)
mid = len(a) // 2, recurse on both halves, mergeDivide and conquerO(nlog⁡n)O(n \log n)
for x in a: heapq.heappush(h, x)n heap operationsO(nlog⁡n)O(n \log n)
for x in a: bisect_left(b, x)n binary searchesO(nlog⁡n)O(n \log n)
a.sort() then one loopSort, then scanO(nlog⁡n)+O(n)=O(nlog⁡n)O(n \log n) + O(n) = O(n \log n)
for i in range(n): for j in range(n)Nested loopsO(n2)O(n^2), not n log n

Is this O(n log n)?

Both halves plus linear combine work, or nn logarithmic steps: that is the n log n signature.

In the wild

Where O(n log n) runs

  • Language sorts

    Python and Java objects use Timsort; C++ std::sort uses introsort. All O(nlog⁡n)O(n \log n).

  • Database ORDER BY

    Tables too big for memory are sorted in runs and merged: external merge sort.

  • Interval problems

    Meeting rooms, merging ranges and calendars: sort by start time, then one scan.

  • Event schedulers

    n pushes and pops on a priority queue cost O(nlog⁡n)O(n \log n).

  • Geometry

    Convex hull and closest pair of points run in O(nlog⁡n)O(n \log n) by sorting or splitting.

  • Signal processing

    The fast Fourier transform turns an O(n2)O(n^2) transform into O(nlog⁡n)O(n \log n).

Recap

Key takeaways

Key points

  • O(n log n) is nn work on each of log⁡2n\log_2 n levels: linear work repeated logarithmically.
  • T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n) solves to O(nlog⁡n)O(n \log n); one half with O(n)O(n) work is only O(n)O(n).
  • Merge sort and heap sort are always O(nlog⁡n)O(n \log n); quick sort is on average, O(n2)O(n^2) worst.
  • Merge sort is stable with O(n)O(n) space; heap sort is O(1)O(1) space; building a heap is O(n)O(n).
  • No comparison sort beats Ω(nlog⁡n)\Omega(n \log n) because log⁡2n!≈nlog⁡2n\log_2 n! \approx n \log_2 n.
  • At a million items: about 20 million steps against a trillion for O(n2)O(n^2).

Sources