Sorting is one of the most fundamental operations in computer science. Arranging data in order, by number, alphabet, timestamp, or any custom rule, is the first step in a huge fraction of algorithms: binary search, two pointers on sorted arrays, sweep-line problems, greedy scheduling, k-way merge, and many more.
There is no single "best" sorting algorithm. The right choice depends on the data type, the size of the input, how much extra memory is available, and whether ties need to preserve the original order. The standard libraries in every modern language bundle a high-quality general-purpose sort, but knowing what runs underneath, and when a specialized sort fits better, lets you choose deliberately instead of always defaulting to sort().
This chapter covers:
Sorting is the process of rearranging the elements of a collection so they follow a defined order. The order is determined by a comparison rule between any two elements:
3 < 5 < 7 < 99 > 7 > 5 > 3"apple" < "banana" < "cherry"The input is an unordered (or partially ordered) sequence; the output is a permutation of the same elements that satisfies the order rule.
Sorting is rarely the end goal in an interview problem. It is almost always a setup step that turns a hard problem into an easy one. Once data is sorted, duplicates sit next to each other, binary search becomes available, two pointers can sweep from both ends, and intervals can be merged in one pass.
Four properties separate sorting algorithms from each other. Every algorithm in this chapter (and the dedicated chapters that follow) can be described by where it lands on each axis.
A comparison-based sort decides the order between two elements by calling a comparison function. The comparison function returns "less than," "equal," or "greater than." Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Heap Sort, and Shell Sort are all comparison-based.
The information-theoretic lower bound for any comparison-based sort is O(n log n). There is a proof: a comparison sort can be modeled as a binary decision tree, and a tree with n! leaves (one per permutation) must have depth at least log₂(n!) = Θ(n log n). No comparison sort can beat this bound in the worst case.
A non-comparison-based sort exploits structural properties of the data, like the range of values or the digits, instead of pairwise comparisons. Counting Sort, Radix Sort, and Bucket Sort fall here. They can run in O(n) or O(n + k) when their preconditions hold, but they only work for specific data types (small integers, fixed-length keys, or values uniformly distributed in a known range).
A sort is stable if it preserves the relative order of elements that compare equal. Two records with the same key stay in their original input order in the output.
Stability matters whenever the data has more than one key and ordering by one key should not scramble a previous order by another key. The most common case is a multi-key sort, like "sort by age, breaking ties by name." A stable sort lets you accomplish this by sorting by name first and then by age; the stability of the second sort preserves the name order within each age group.
Bubble Sort, Insertion Sort, Merge Sort, Counting Sort, Radix Sort, and Bucket Sort are stable in their standard form. Selection Sort, Quick Sort, Heap Sort, and Shell Sort are not stable in their basic implementations.
An in-place sort uses only O(1) or O(log n) extra space, modifying the input array directly. Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, Heap Sort, and Shell Sort are in-place.
An out-of-place sort allocates additional memory proportional to the input. Merge Sort uses O(n) auxiliary space for the merge buffer; Counting Sort uses O(k) space for the count array; Radix Sort uses O(n + k) space.
In-place sorts win when memory is tight or the dataset barely fits in memory. Out-of-place sorts often win on stability and parallelism, because their auxiliary buffers can be used to preserve ties and merge independent chunks.
An internal sort assumes the data fits in main memory. Every algorithm covered in this course is internal.
An external sort handles data too large for RAM by streaming chunks from disk, sorting them in memory, and merging the sorted runs back together. External sorting is rare in interview problems but appears in follow-up questions like "what if the input is 10 TB?" The answer is almost always "external merge sort": split into RAM-sized chunks, sort each chunk in memory, write to disk, then do a k-way merge of the sorted chunks using a min-heap.
The 10 sorting algorithms covered in this course, ranked by worst-case time complexity:
k is the range of values for Counting/Bucket Sort; d is the number of digits for Radix Sort. The Shell Sort average is gap-sequence-dependent; Ciura's sequence achieves roughly O(n^1.3) in practice.
A few patterns in the table:
n < 50) or as components inside other algorithms.The decision tree below maps common situations to algorithms.
A few rules of thumb that the chart simplifies:
n ≤ 50 or nearly sorted arrays, Insertion Sort beats more sophisticated algorithms because of low constants. This is why library sorts (Timsort, Introsort) fall back to Insertion Sort on small subarrays.std::sort in C++ historically uses Introsort, which is Quick Sort with a Heap Sort safety net).Arrays.sort for objects uses Timsort (a hybrid of Merge Sort and Insertion Sort) for this reason.In an interview, calling the language's built-in sort is almost always correct. The implementations are well-tested and run in O(n log n). This section shows the basic idiom in each language, then how to sort by a custom rule.
The JavaScript and TypeScript default deserves a callout. [10, 2, 1].sort() yields [1, 10, 2] because the default comparator converts numbers to strings and orders them lexicographically. Always pass (a, b) => a - b when sorting numbers in JS/TS.
Sorting by a derived key (descending order, second field of an object, string length, frequency) is a common requirement. Every language exposes a way to specify the comparison.
The two universal idioms are:
a comes before b, zero if equal, positive if a comes after b. This is the lowest-level form.A few language-specific notes:
Arrays.sort on a primitive int[] does not accept a comparator. Box to Integer[] (or use IntStream.boxed) when a custom order is needed. Collections.sort on a List accepts a Comparator.key= is almost always cleaner than cmp= (which was removed in Python 3 anyway). Returning a tuple from the key function gives multi-key sort for free.sort.Slice is unstable; sort.SliceStable is stable. Both take a less function with index arguments rather than element arguments.sort_by_key clones the key for each comparison; for expensive keys, sort_by_cached_key computes each key once.true if the first argument should come before the second. A non-strict comparator (returning true on equal elements) causes undefined behavior.In interviews, the sort itself is almost never the answer. The pattern is: sort the input, then run a simpler algorithm on the sorted version. The cost is O(n log n) up front; the payoff is that the harder part becomes O(n).
The patterns below cover the common cases where sorting comes first.
Once data is sorted, two pointers can sweep from both ends or in lockstep and answer pair-sum questions, partition questions, or merge questions in O(n) time.
Classic examples: Two Sum II (sorted version), 3Sum, 4Sum, Container With Most Water.
Most interval problems begin with "sort intervals by start time." Once sorted, a single pass merges overlaps, finds gaps, or schedules non-overlapping intervals.
Classic examples: Merge Intervals (LC 56), Insert Interval (LC 57), Non-overlapping Intervals (LC 435), Meeting Rooms II (LC 253).
Many greedy algorithms work by sorting by a "value" and picking elements in order. The sort proves that the local choice is also the global choice.
Classic examples: Activity Selection (sort by end time), Largest Number (LC 179) (custom comparator on string concatenation), Reorganize String (sort by frequency), Minimum Cost to Connect Sticks (greedy with a heap, which is a sort in disguise).
Sorting characters within each string gives a canonical form that hash maps can group on.
Classic examples: Group Anagrams (LC 49) uses sorted strings as map keys; Valid Anagram (LC 242) is a special case of comparing sorted forms.
Some "how many pairs satisfy X" problems reduce to counting inversions during merge sort. Merge Sort handles this in O(n log n) by counting cross-pairs at every merge step.
Classic examples: Count of Smaller Numbers After Self (LC 315), Reverse Pairs (LC 493), Count of Range Sum (LC 327).
Sorting is rarely the main goal, but it is a common first step. Knowing the four classifications, comparison vs not, stable vs not, in-place vs not, internal vs external, lets you reason about sorting in terms of trade-offs. The comparison table above is the practical summary: 10 algorithms, plus their best/average/worst times, space, and stability.
For day-to-day work, three sorts cover most of the ground:
The chapters that follow each take one algorithm and go deep on how it works, how to implement it, and the edge cases that matter in interviews. With the classification in hand, the differences between them are easier to see and the choice in any given problem becomes a deliberate one rather than a default.