External Sorting

Idea

External sorting handles data too large for memory, using external storage (disk). Split the big file into memory-fit chunks, sort each, then multiway-merge.

External sorting

Click "Step forward" to watch the algorithm state change.

Common approach

Multiway merge sort

  • Split into chunks, load each into memory and sort (e.g., merge sort).
  • Merge sorted chunks (“runs”) via multiway merge.
  • Use 2-way, 4-way, or multiway merging to reduce passes.

Scenarios

  • Large DBs, search logs, big-data analytics
  • Any sort where the whole dataset cannot fit in memory

Complexity

  • Sorting phase: O(nlog⁡n)O(n\log n) (per chunk)
  • Merge phase: O(nlog⁡kn)O(n\log_k n), kk = merge ways
  • Overall: O(nlog⁡n)O(n\log n)
  • Space: dominated by disk I/O and buffer sizes

Exercises

Exercise 1

Describe the basic flow and use cases of external sorting.

External SortingRun GenerationMulti-way Merge

Approach: Sort in chunks plus multi-way merging, which suits very large data.

Steps:

  1. Sort the chunks in memory and generate sorted runs
  2. Merge the runs in multi-way fashion into the final file
  3. Applies when the data no longer fits in memory

Answer: Chunked sorting plus merging, which suits sorting very large data.

Exercise 2

Common merge ways and their complexity?

External SortingMulti-way MergeTime Complexity

Approach: Two-way and multi-way merging, and their complexity.

Steps:

  1. Two-way, four-way and multi-way merging
  2. Complexity O(nlog⁡kn)O(n\log_k n), where kk is the number of ways

Answer: Multi-way merging is commonly used, with complexity O(nlog⁡kn)O(n\log_k n).

Found an issue with this content?

Tell us what could be improved.