Skip to main content

Summary: Sorting

Everything on one page, to review the chapter before moving on. The comparison lesson has the full table, with comparisons, moves and real measurements.

Key ideas​

  • Sorting is one of the most frequent operations in computing, and a classic benchmark for algorithm design (The Sorting Problem).
  • The simple algorithms (bubble, insertion, selection) are O(n2)O(n^2). Insertion sort is the best of them in practice and is linear on almost sorted data.
  • Quicksort partitions around a pivot: O(nlog⁡n)O(n \log n) on average, O(n2)O(n^2) in the worst case, and usually the fastest in practice.
  • Mergesort sorts by merging: O(nlog⁡n)O(n \log n) in every case and stable. No comparison-based algorithm can beat O(nlog⁡n)O(n \log n) in the worst case.
  • Choose according to the size, the initial order of the data, the need for stability, the available memory and the cost of moves, and prefer the library implementation in real programs (Comparing Sorting Algorithms).

At a glance​

AlgorithmBestAverageWorstIn placeStable
BubbleO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)YesYes
Bubble with sentinelO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)YesYes
Direct insertionO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)YesYes
Direct selectionO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)YesNo
MergesortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)No (O(n)O(n))Yes
QuicksortO(nlog⁡n)O(n \log n)O(nlog⁡n)O(n \log n)O(n2)O(n^2)Yes (stack)No

Which one to use​

  • Small or almost sorted data: insertion sort.
  • General purpose, fastest in practice: Quicksort with median-of-three.
  • Guaranteed O(nlog⁡n)O(n \log n), stability, or data in external memory: Mergesort.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.