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 . Insertion sort is the best of them in practice and is linear on almost sorted data.
- Quicksort partitions around a pivot: on average, in the worst case, and usually the fastest in practice.
- Mergesort sorts by merging: in every case and stable. No comparison-based algorithm can beat 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
| Algorithm | Best | Average | Worst | In place | Stable |
|---|---|---|---|---|---|
| Bubble | Yes | Yes | |||
| Bubble with sentinel | Yes | Yes | |||
| Direct insertion | Yes | Yes | |||
| Direct selection | Yes | No | |||
| Mergesort | No () | Yes | |||
| Quicksort | 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 , stability, or data in external memory: Mergesort.
Saved only in your browser
Questions, or something wrong?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.