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
Merge two sorted piles
A whole level handles every map
Distinguish a search from a full sort
Choose the right guarantee
0:00 / 4:17
O(n log n) linearithmic time
1:23·Reel
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
Do n work per level. On every level each item is touched a constant number of times while merging or partitioning
Multiply. n work × log n levels = n log n, the cost of every efficient comparison sort
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 log2n 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 n items once, merging or partitioning.
log n levels
Halving n down to pieces of size 1 takes ⌈log2n⌉ levels.
The sorting sweet spot
No comparison sort can beat it, and it is far closer to O(n) than to O(n2).
The one-line formula
work per leveln×levelslog2n=nlog2n
For n=1,024 that is 1,024×10≈10,000 steps. A quadratic algorithm would need about a million.
The picture
Why n × log n
The recursion tree, level by level
flowchart TD
L0["Level 0: 1 piece of size n, n work"] --> L1["Level 1: 2 pieces of size n/2, n work"]
L1 --> L2["Level 2: 4 pieces of size n/4, n work"]
L2 --> L3["Level 3: 8 pieces of size n/8, n work"]
L3 --> DOTS["..."]
DOTS --> LK["Level log2(n): n pieces of size 1"]
LK --> SUM["Total: n work on each of log2(n) levels"]
The pieces get smaller but more numerous. Their sizes always add up to n, so every level costs the same.
Merge sort on 16 items
Level
Pieces
Size of each
Work on the level
0
1
16
16
1
2
8
16
2
4
4
16
3
8
2
16
4
16
1
base case
Four merge levels of 16 work each: 16×log216=64.
The math
The divide and conquer recurrence
Merge sort splits the problem into two halves, solves each recursively, and spends O(n) combining them. Written as a recurrence and unrolled, the cn term appears once per level.
After k=log2n levels the pieces have size 1. The result is O(nlogn).
The master theorem view
T(n)=aT(n/b)+O(nd),a=bd⇒T(n)=O(ndlogn)
Merge sort has a=2 subproblems of size n/b=n/2 and O(n1) combine work. Since 2=21, the answer is O(nlogn).
Example 1
Merge sort: always n log n
Splitting and merging [38, 27, 43, 3, 9, 82, 10]
flowchart TD
A["38 27 43 3 9 82 10"] --> B["38 27 43 3"]
A --> C["9 82 10"]
B --> D["38 27, merges to 27 38"]
B --> E["43 3, merges to 3 43"]
C --> F["9 82, merges to 9 82"]
C --> G["10"]
D --> H["Merge to 3 27 38 43"]
E --> H
F --> I["Merge to 9 10 82"]
G --> I
H --> J["Final: 3 9 10 27 38 43 82"]
I --> J
Three levels of splitting (⌈log27⌉=3), then merges back up. This run makes 14 comparisons, under the 3×7=21 bound.
Python
defmerge_sort(arr):iflen(arr) <= 1: # base case: already sortedreturn arr mid = len(arr) // 2 left = merge_sort(arr[:mid]) # T(n/2) right = merge_sort(arr[mid:]) # T(n/2)returnmerge(left, right) # O(n)defmerge(left, right): result = [] i = j = 0while i < len(left) and j < len(right):if left[i] <= right[j]: # <= keeps equal items in order (stable) result.append(left[i]) i += 1else: 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(nlogn) 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) 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
flowchart TD
A["Pick a pivot: the middle or a random element"] --> B["Swap the pivot to the end; i = lo"]
B --> C{"Next j: arr[j] < pivot?"}
C -- yes --> D["Swap arr[i] and arr[j]; i += 1"]
C -- no --> E["Leave it"]
D --> F{"More j before the pivot?"}
E --> F
F -- yes --> C
F -- no --> G["Swap the pivot into arr[i]: final place"]
G --> H["Recurse on lo..i-1 and i+1..hi"]
Partitioning is one O(n) scan. How good the pivot is decides how many levels there are.
Good pivots against bad pivots
balanced splitsT(n)=2T(n/2)+O(n)=O(nlogn)pivot is the min or maxT(n)=T(n−1)+O(n)=O(n2)
With a pivot that always lands at an end, the levels shrink by one item instead of by half: n+(n−1)+⋯+1=2n(n+1).
Example 3
Heap sort: n log n in place
Heap sort in four moves
1Build a max heapO(n), sift down from the last parent
Each extraction walks one root-to-leaf path in a tree of height ⌊log2n⌋.
Head to head
The O(n log n) sorts compared
Algorithm
Best
Average
Worst
Extra space
Stable
Merge sort
O(nlogn)
O(nlogn)
O(nlogn)
O(n)
yes
Quick sort
O(nlogn)
O(nlogn)
O(n2)
O(logn) stack
no
Heap sort
O(nlogn)
O(nlogn)
O(nlogn)
O(1)
no
Timsort
O(n)
O(nlogn)
O(nlogn)
O(n)
yes
Bubble sort
O(n)
O(n2)
O(n2)
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(nlogn) and stable. Best for linked lists and external sorting.
Quick sort
Average O(nlogn), in place, fastest in practice. Use random pivots.
Heap sort
Always O(nlogn) with 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
n
O(n)
O(nlogn)
O(n2)
10
10
33
100
100
100
664
10,000
1,000
1,000
9,966
1,000,000
10,000
10,000
132,877
100,000,000
1,000,000
1,000,000
about 20 million
1012
O(nlogn) is much closer to O(n) than to O(n2): only about 20 times linear at a million.
Predicting a running time
103log2103106log2106≈103⋅10106⋅20=2000⇒10 ms×2000=20 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
flowchart TD
Q1{"a < b?"} -- yes --> Q2{"b < c?"}
Q1 -- no --> Q3{"a < c?"}
Q2 -- yes --> L1["a b c"]
Q2 -- no --> Q4{"a < c?"}
Q4 -- yes --> L2["a c b"]
Q4 -- no --> L3["c a b"]
Q3 -- yes --> L4["b a c"]
Q3 -- no --> Q5{"b < c?"}
Q5 -- yes --> L5["b c a"]
Q5 -- no --> L6["c b a"]
Any comparison sort is a tree of yes or no questions. It needs one leaf per ordering, 3!=6 here, so some input needs 3 comparisons.
The lower bound
2h≥n!⇒h≥log2n!≈nlog2n−1.44n⇒Ω(nlogn)
A binary tree of height h has at most 2h leaves. By Stirling's formula log2n! grows like nlog2n. For n=7: log25040≈12.3, so every comparison sort needs at least 13 comparisons on some input.
Pattern spotting
Spotting O(n log n) in code
Code shape
What it is
Cost
sorted(arr) or arr.sort()
Built-in sort (Timsort)
O(nlogn)
mid = len(a) // 2, recurse on both halves, merge
Divide and conquer
O(nlogn)
for x in a: heapq.heappush(h, x)
n heap operations
O(nlogn)
for x in a: bisect_left(b, x)
n binary searches
O(nlogn)
a.sort() then one loop
Sort, then scan
O(nlogn)+O(n)=O(nlogn)
for i in range(n): for j in range(n)
Nested loops
O(n2), not n log n
Is this O(n log n)?
flowchart TD
Q1{"Does it sort, or call sorted()?"} -- yes --> NLOGN["O(n log n)"]
Q1 -- no --> Q2{"Split in half, recurse on both halves, O(n) to combine?"}
Q2 -- yes --> NLOGN
Q2 -- no --> Q3{"n items, each doing an O(log n) step?"}
Q3 -- yes --> NLOGN
Q3 -- no --> Q4{"Recurse on only one half?"}
Q4 -- yes --> ONE["O(log n) with O(1) work, O(n) with O(n) work"]
Q4 -- no --> MORE["Count the work another way"]
Both halves plus linear combine work, or n 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(nlogn).
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(nlogn).
Geometry
Convex hull and closest pair of points run in O(nlogn) by sorting or splitting.
Signal processing
The fast Fourier transform turns an O(n2) transform into O(nlogn).
Recap
Key takeaways
Key points
O(n log n) is n work on each of log2n levels: linear work repeated logarithmically.
T(n)=2T(n/2)+O(n) solves to O(nlogn); one half with O(n) work is only O(n).
Merge sort and heap sort are always O(nlogn); quick sort is on average, O(n2) worst.
Merge sort is stable with O(n) space; heap sort is O(1) space; building a heap is O(n).
No comparison sort beats Ω(nlogn) because log2n!≈nlog2n.
At a million items: about 20 million steps against a trillion for O(n2).