AlgoMaster Logo

Introduction to Sorting

10 min readUpdated June 4, 2026
Listen to this chapter
Unlock Audio

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:

  • What sorting means and why it matters
  • The four ways sorting algorithms are classified
  • A comparison table of all 10 sorting algorithms in this course
  • How to pick the right algorithm
  • Built-in sorts and custom comparators across languages
  • Sort as a preprocessing step for harder problems

What is Sorting?

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:

  • Numeric ascending: 3 < 5 < 7 < 9
  • Numeric descending: 9 > 7 > 5 > 3
  • Lexicographic: "apple" < "banana" < "cherry"
  • Custom: by second field, by string length, by frequency, etc.

The input is an unordered (or partially ordered) sequence; the output is a permutation of the same elements that satisfies the order rule.

5
0
2
1
8
2
1
3
9
4
3
5
Before
1
0
2
1
3
2
5
3
8
4
9
5
After

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.

How Sorting Algorithms Are Classified

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.

1. Comparison-Based vs Non-Comparison-Based

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).

2. Stable vs Unstable

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.

3. In-Place vs Out-of-Place

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.

4. Internal vs External

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.

Comparison Table

The 10 sorting algorithms covered in this course, ranked by worst-case time complexity:

Scroll
AlgorithmBest TimeAverage TimeWorst TimeSpaceStableIn-placeType
Bubble SortO(n)O(n²)O(n²)O(1)YesYesComparison
Selection SortO(n²)O(n²)O(n²)O(1)NoYesComparison
Insertion SortO(n)O(n²)O(n²)O(1)YesYesComparison
Shell SortO(n log n)O(n^1.3)*O(n²)O(1)NoYesComparison
Merge SortO(n log n)O(n log n)O(n log n)O(n)YesNoComparison
Quick SortO(n log n)O(n log n)O(n²)O(log n)NoYesComparison
Heap SortO(n log n)O(n log n)O(n log n)O(1)NoYesComparison
Counting SortO(n + k)O(n + k)O(n + k)O(k)YesNoNon-comparison
Radix SortO(d · (n + k))O(d · (n + k))O(d · (n + k))O(n + k)YesNoNon-comparison
Bucket SortO(n + k)O(n + k)O(n²)O(n + k)YesNoNon-comparison

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:

  • Bubble, Selection, Insertion are O(n²) algorithms. They are simple, in-place, and fine for very small inputs (say, n < 50) or as components inside other algorithms.
  • Merge, Quick, Heap are the general-purpose choices. All three hit O(n log n) average time. Merge wins on stability, Quick wins on practical speed and memory, Heap wins on guaranteed worst case.
  • Counting, Radix, Bucket beat O(n log n) by trading generality for speed. They require special structure (small integer keys, fixed-length keys, or uniform distribution).
  • Shell Sort is a curious middle ground: it improves Insertion Sort with a gap sequence but never quite reaches O(n log n).

Choosing the Right Sort

The decision tree below maps common situations to algorithms.

A few rules of thumb that the chart simplifies:

  • For 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.
  • For general-purpose, in-memory sorting, Quick Sort has the best constants and is the default in many language libraries (std::sort in C++ historically uses Introsort, which is Quick Sort with a Heap Sort safety net).
  • When stability matters, Merge Sort is the standard choice. Java's Arrays.sort for objects uses Timsort (a hybrid of Merge Sort and Insertion Sort) for this reason.
  • When worst-case O(n log n) is required (real-time systems, security-sensitive contexts where adversarial input could trigger Quick Sort's O(n²)), Heap Sort is the safe choice.
  • For specialized inputs, the non-comparison sorts can be dramatically faster. Sorting one million 32-bit integers with Radix Sort can be 5-10× faster than Quick Sort.

Built-in Sorts

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.

Sorting an Array Ascending

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.

Custom Comparators

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:

  • Comparator function: returns a negative number if a comes before b, zero if equal, positive if a comes after b. This is the lowest-level form.
  • Key function: returns a sortable value extracted from each element. The library sorts by the keys, which is cleaner when applicable.

A few language-specific notes:

  • Java: 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.
  • Python: 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.
  • Go: sort.Slice is unstable; sort.SliceStable is stable. Both take a less function with index arguments rather than element arguments.
  • Rust: sort_by_key clones the key for each comparison; for expensive keys, sort_by_cached_key computes each key once.
  • C++: The comparator returns true if the first argument should come before the second. A non-strict comparator (returning true on equal elements) causes undefined behavior.

Sort as a Preprocessing Step

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.

1. Two Pointers on a Sorted Array

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.

2. Merging Intervals

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).

3. Greedy Choices

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).

4. Group / Anagram

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.

5. Counting Inversions / Rank Queries

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).

Wrapping Up

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:

  • Quick Sort / Introsort for general in-place sorting (the default in most language libraries).
  • Merge Sort / Timsort when stability or worst-case O(n log n) matters.
  • Counting / Radix Sort when the input is small integers or fixed-length keys and you need to beat O(n log n).

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.