Sorting Algorithms

How the main sorting algorithms work, what each one costs, and how to use a built-in sort with a custom key. In practice, sorting is most often the first step that makes the real algorithm simple.

Overview

You will rarely be asked to write a sort from scratch. You will often sort first, because sorted data has structure that other techniques rely on. The sort costs O(n log n), and the step after it is often a single O(n) pass.

What to know: when sorting helps, what it costs, whether it loses information you need, and how to write the comparison.

Each section below follows the same shape: the rule first, then the rule on a small example, then the trap to avoid.

Why sorting matters

The rule: sort first when the step after it needs one of four kinds of structure.

  • Equal values sit next to each other. You can find duplicates and group items in one pass, as in Contains Duplicate and Group Anagrams.
  • Values are in order. You can use binary search or two pointers, as in Three Sum and Find K Closest Elements.
  • Intervals are ordered by start. You can merge them or check overlaps in one pass, as in Merge Intervals and Meeting Rooms.
  • Items are ranked by a greedy key. You can take the best item first, as in Non-overlapping Intervals and Car Fleet.

> [!WARNING] > Sorting can lose information you need, such as the original indexes. Check for that before you sort.

Sign up free to read the full topic

More Coding & DSA topics

Start free on Cariara · Coding problems · System design studio