Algorithms

Sorting Algorithms

Sorting algorithms rearrange a collection of items into order. The right choice depends on input size, value range, memory limits, and whether equal items must keep their original order. This guide compares 13 sorting algorithms in one table, then explains how to choose between them.

At a glance

Every sorting algorithm trades the same few things: time, extra memory, and whether equal items keep their order. No single algorithm wins on all three. The best choice depends on which one is scarce for you.

The table below covers 13 algorithms, from simple ones like bubble sort to the hybrids that real libraries use. Use it to pick a candidate. Then open each page for a step-by-step interactive visualization and a short video.

Algorithms Time (avg)Time (worst)SpaceStableIn-placeBest for
Merge Sort O(n log n)O(n log n)O(n)YesNoLinked lists, external sorts, predictable performance
Quick Sort O(n log n)O(n²)O(log n)NoYesGeneral-purpose in-memory sorting; cache-friendly
Bubble Sort O(n²)O(n²)O(1)YesYesTeaching, near-sorted small inputs
Counting Sort O(n + k)O(n + k)O(n + k)YesNoBounded integer keys (ages, grades, byte values)
Insertion Sort O(n²)O(n²)O(1)YesYesSmall or nearly sorted inputs; the finishing step inside hybrids
Selection Sort O(n²)O(n²)O(1)NoYesTiny inputs where writes are expensive (flash, EEPROM)
Heapsort O(n log n)O(n log n)O(1)NoYesGuaranteed worst case with no extra memory
Shell Sort Depends on gaps (about O(n^1.3) in practice)O(n²) with Shell’s gaps; O(n log² n) with the best knownO(1)NoYesMid-size arrays with no recursion or extra memory (embedded code)
Radix Sort O(d(n + k))O(d(n + k))O(n + k)YesNoFixed-width integers, strings of equal length, IDs
Bucket Sort O(n + k)O(n²)O(n + k)Yes (if the bucket sort is stable)NoEvenly distributed numbers such as floats in [0, 1)
Timsort O(n log n)O(n log n)O(n)YesNoReal-world data with ordered stretches; sorting objects
Introsort O(n log n)O(n log n)O(log n)NoYesGeneral-purpose in-memory sorting of primitives (C++ std::sort)
Patience Sort O(n log n)O(n log n)O(n)NoNoLongest increasing subsequence; learning how piles encode order

Each algorithm in depth

Click any card for the full article with an interactive visualization, complexity analysis, code examples, and FAQ.

Which sorting algorithm should I reach for?

In almost every real program, call your language's built-in sort. It is already a tuned hybrid. Python's sort and Java's object sort use Timsort. C++'s std::sort is based on introsort. You rarely beat them by hand.

When you do need to choose, this is a fair guide:

  • Need a guaranteed worst case and stability: merge sort. It pays with O(n) extra memory.
  • Need a guaranteed worst case and no extra memory: heapsort. It is not stable and is slower in practice than quick sort.
  • Fastest average speed in memory: quick sort, or introsort, which fixes quick sort's bad case.
  • Data that is often partly sorted: Timsort, or insertion sort for small inputs.
  • Integer keys in a small range: counting sort.
  • Fixed-width integers or equal-length strings: radix sort.
  • Numbers spread evenly over a range: bucket sort.
  • Writes are very expensive: selection sort does at most n swaps.
  • A simple, no-recursion sort for mid-size arrays: shell sort.

Bubble sort is mainly for teaching. Patience sort does sort, but it is best known for finding the longest increasing subsequence.

Stable and in-place sorts, explained

A stable sort keeps equal items in their original order. Say you sort a table of (name, score) rows by score. With a stable sort, rows with the same score stay in the order they had before. That lets you sort by name first, then by score, and get rows ordered by score with names in order inside each score. Stable: merge sort, insertion sort, bubble sort, counting sort, radix sort, Timsort, and bucket sort when its inner sort is stable. Not stable: quick sort, heapsort, selection sort, shell sort, introsort.

An in-place sort uses only a small, fixed or logarithmic amount of extra memory, besides the array itself. Insertion sort, selection sort, bubble sort, heapsort, and shell sort use O(1) extra space. Quick sort and introsort use O(log n) for the recursion stack, which is still counted as in-place. Merge sort, Timsort, counting sort, radix sort, and bucket sort need O(n) extra space.

Why comparison sorts cannot beat O(n log n)

A comparison sort learns about the data only by asking "is a less than b?". Each answer is yes or no. With n items there are n! possible orderings, and the algorithm must be able to tell them apart. A sequence of k yes/no answers can separate at most 2k cases, so it needs 2k ≥ n!. Taking logs, k ≥ log2(n!), which grows like n log n. So in the worst case, every comparison sort needs on the order of n log n comparisons. Merge sort and heapsort reach this bound. Quick sort reaches it on average.

Non-comparison sorts: counting, radix, and bucket

The lower bound only applies to sorts that compare. Counting sort reads the key itself and uses it as an array index, so it never compares two items. That gives O(n + k) time for keys in a range of size k. Radix sort applies a stable counting sort to one digit at a time and runs in O(d(n + k)) for d digits in base k. Bucket sort splits the range into buckets and sorts each one. These are very fast when the keys fit their model. They get slow or memory-hungry when the key range is huge, or when the data is clumped into a few buckets.

Hybrids: how real libraries sort

Each basic algorithm has a weak spot. Quick sort has an O(n²) worst case. Merge sort needs extra memory. Insertion sort is slow on large arrays but very fast on tiny ones. Hybrids combine them.

Introsort runs quick sort, switches to heapsort if recursion gets too deep, and finishes small pieces with insertion sort. This is the idea behind C++ std::sort. Timsort looks for runs that are already ordered, extends short runs with insertion sort, and merges runs like merge sort. It is stable and takes O(n) time on already sorted input. Python and Java (for objects) use it. Shell sort is another way to speed up insertion sort. It moves items over large gaps first.

Simple sorts and why they still matter

Insertion sort, selection sort, and bubble sort are all O(n²) on average. Their loops are short and have no recursion, so on small arrays they can beat fancier methods. That is why hybrids hand small pieces to insertion sort. Among the three, insertion sort is the practical one. It adapts to nearly sorted input, running in O(n) when little is out of place. Selection sort does the fewest writes. Bubble sort has few real uses beyond teaching.

Frequently asked questions

Which sorting algorithm is the fastest?

There is no single fastest one. For general data in memory, tuned hybrids such as introsort (C++ std::sort) and Timsort (Python, Java objects) are the fastest in practice. For small-range integers, counting sort or radix sort can beat them because they do not compare items.

Which sorting algorithm should I use?

Use your language's built-in sort. If you must pick one yourself, use merge sort when you need stability or a guaranteed O(n log n), quick sort or introsort for fast in-memory sorting, heapsort when you need a worst-case guarantee with no extra memory, and counting or radix sort for bounded integer keys.

What does it mean for a sort to be stable?

A stable sort keeps items with equal keys in the same relative order they had in the input. This matters when you sort records by more than one field. Merge sort, insertion sort, Timsort, counting sort, and radix sort are stable. Quick sort, heapsort, and selection sort usually are not.

What is an in-place sort?

An in-place sort rearranges the array using only a small amount of extra memory, such as O(1) or O(log n). Insertion sort, selection sort, heapsort, and quick sort are in-place. Merge sort, Timsort, and counting sort need O(n) extra space.

Why can't comparison sorting beat O(n log n)?

With n items there are n! possible orderings. Each comparison gives a yes or no answer, so k comparisons can tell apart at most 2^k orderings. To cover n! orderings you need k of at least log2(n!), which is about n log n. This holds in the worst case for any algorithm that only compares pairs.

How can radix and counting sort be faster than O(n log n)?

They do not compare items. Counting sort uses each key as an array index, and radix sort sorts digit by digit. The lower bound only applies to comparison sorts. The price is that keys must be integers or fixed-width strings, and the key range or digit count has to be reasonable.

What sort do Python, Java, and C++ use?

Python's list.sort and sorted use Timsort. Java uses Timsort for object arrays and a dual-pivot quick sort for primitive arrays. C++ std::sort is usually an introsort, which is quick sort with a heapsort fallback and insertion sort for small pieces. Exact choices can vary by version and library.

Is bubble sort ever a good choice?

Rarely. It is O(n²) on average and worse in practice than insertion sort, which is just as simple and also stable and in-place. Bubble sort is mostly useful for teaching how comparing and swapping neighbors works.