Skip to main content

Comparing Sorting Algorithms

9 min readRead first: Quicksort Β· Beyond Quadratic Sorting

We have studied many sorting algorithms. This lesson brings them together: we compare their behavior with measurements, summarize their properties, give practical guidelines for choosing one, and introduce the sorting of data that does not fit in main memory.

What you will learn in this lesson
  • How the algorithms of the chapter compare in practice, for sorted, random and reverse inputs.
  • How to interpret those measurements in the light of their theoretical complexity.
  • Practical criteria to choose a sorting algorithm.
  • The basic ideas of external sorting.

The Complexity of Each Algorithm​

🧠 Checkpoint: Before looking at the table

Question: For each algorithm, choose one option: "O(n2)O(n^2) in all cases", "between O(n)O(n) and O(n2)O(n^2), depending on the case", or "between O(nlog⁑n)O(n \log n) and O(n2)O(n^2), depending on the case". (a) Bubble; (b) bubble with sentinel; (c) direct insertion; (d) direct selection; (e) Quicksort.

Answer: (a) O(n2)O(n^2) in all cases; (b) between O(n)O(n) and O(n2)O(n^2); (c) between O(n)O(n) and O(n2)O(n^2); (d) O(n2)O(n^2) in all cases; (e) between O(nlog⁑n)O(n \log n) and O(n2)O(n^2).

AlgorithmBestAverageWorstComparisonsMovesIn placeStableAdaptive
BubbleO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)always n(nβˆ’1)2\frac{n(n-1)}{2}many swapsYesYesNo
Bubble with sentinelO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)from nβˆ’1n-1 to n(nβˆ’1)2\frac{n(n-1)}{2}many swapsYesYesPartly
Direct insertionO(n)O(n)O(n2)O(n^2)O(n2)O(n^2)from nβˆ’1n-1 to n(nβˆ’1)2\frac{n(n-1)}{2}shifts = inversionsYesYesYes
Direct selectionO(n2)O(n^2)O(n2)O(n^2)O(n2)O(n^2)always n(nβˆ’1)2\frac{n(n-1)}{2}at most nβˆ’1n - 1 swapsYesNoNo
MergesortO(nlog⁑n)O(n \log n)O(nlog⁑n)O(n \log n)O(nlog⁑n)O(n \log n)No (O(n)O(n))YesNo (basic version)
QuicksortO(nlog⁑n)O(n \log n)O(nlog⁑n)O(n \log n)O(n2)O(n^2)Yes (stack)NoNo

Measurements​

Small sizes: the classic comparison​

A classic comparison measures the execution times for n=256n = 256 and n=512n = 512 elements, with sorted, random and inverse (reverse-sorted) inputs. Some of the most interesting patterns:

  • Bubble sort is the slowest in almost every case, and it is slow even on sorted data. With a sentinel (or in its bidirectional version), the sorted case becomes almost free.
  • Direct insertion is about 3 times faster than bubble on random data, and practically instantaneous on sorted data. Binary insertion reduces comparisons, which helps a little on inverse data, but it is clearly slower on sorted data.
  • Direct selection takes about the same time in the three cases: its comparisons do not depend on the input.
  • Quicksort and Mergesort are much faster than the simple algorithms already with a few hundred elements, and Quicksort is the fastest on random data.
  • Going from 256 to 512 elements, the times of the simple algorithms multiply by about 4, and those of the efficient ones by a little more than 2, as their complexities predict.

Medium sizes, without optimization​

We measured the course implementations for n=8,000n = 8{,}000, without optimization (-Xint, times in milliseconds):

AlgorithmSortedRandomReverse
Bubble5421,1321,592
Bubble with sentinel0.11,1511,684
Bidirectional bubble0.11,0801,746
Direct insertion0.2329670
Binary insertion2.4227430
Direct selection509507540
Mergesort3.14.53.8
Quicksort1.63.71.8

The same patterns appear, and the gap between the families is now enormous: on random data, Quicksort is about 300 times faster than bubble sort. (Many values of the efficient algorithms are below the 50 ms reliability threshold; they indicate orders of magnitude, not precise times.)

Large sizes, with optimization​

The simple algorithms are hopeless for large inputs: extrapolating, bubble sort would need hours for a million random elements. For the efficient algorithms, we measured with the JIT optimizer enabled (best of three runs, milliseconds), and included Java's Arrays.sort as a reference:

AlgorithmnnSortedRandomReverse
Mergesort1,000,0003214956
4,000,000151663279
Quicksort1,000,0001112711
4,000,0006356447
Arrays.sort1,000,0000850
4,000,00023984

Some observations:

  • Multiplying nn by 4 multiplies the random times by a little more than 4 for the O(nlog⁑n)O(n \log n) algorithms, as expected.
  • Quicksort is the fastest of the course implementations on random data, with Mergesort behind it. Mergesort pays for copying the elements to the auxiliary array and back.
  • Arrays.sort (dual-pivot Quicksort, heavily tuned) beats all of them, and it detects already sorted (and reverse-sorted) inputs, sorting them almost instantly. Library implementations are the result of decades of engineering: use them unless you have a good reason not to.

Choosing a Sorting Algorithm​

There is no algorithm that is best in every situation. Some practical guidelines:

  • In real programs, use the library: Arrays.sort, Collections.sort or List.sort in Java. They are correct, fast and well tested. Implement your own algorithm only for learning, or for very special needs.
  • Small arrays (a few dozen elements): insertion sort. Its low overhead beats the efficient algorithms for small nn.
  • Almost sorted data: insertion sort (or an adaptive algorithm such as TimSort). Avoid Quicksort with the first or last element as pivot.
  • Large arrays, general case: Quicksort with a good pivot strategy, usually the fastest in practice.
  • A guaranteed worst case (real-time systems, or inputs that could be chosen by an adversary): Mergesort, which is O(nlog⁑n)O(n \log n) in every case.
  • Stability required (sorting records by several criteria): Mergesort (or insertion sort for small inputs). Quicksort and selection sort are not stable.
  • Very little extra memory: Quicksort, which only needs its stack (keep it O(log⁑n)O(\log n) by recursing on the smaller part). Mergesort needs O(n)O(n) extra memory.
  • Very expensive moves (large records that must be physically moved): selection sort for small inputs, since it moves each element at most once; for large inputs, sort an array of indices or references instead.
  • Data that does not fit in memory: external sorting (next section).
🧠 Checkpoint: Choose the algorithm

Question: Which algorithm would you use in each case? (a) A list of 30 students to be sorted by grade, keeping the alphabetical order of students with the same grade. (b) 50 million random integers in a device with almost no free memory. (c) A large array that is already sorted except for a few elements appended at the end.

Answer: (a) A stable algorithm: with only 30 elements, insertion sort is perfect (or the library's stable sort for objects). (b) Quicksort with a good pivot, recursing on the smaller part so that the stack stays O(log⁑n)O(\log n); Mergesort would need another array of 50 million elements. (c) Insertion sort (or TimSort): almost every element is already in place, so it is close to linear, while Quicksort with the first element as pivot would be quadratic.


External Sorting​

All the algorithms of this chapter are internal: they assume that the whole array is in main memory, where any element can be accessed quickly. When the data does not fit in memory (for example, a file of hundreds of gigabytes), it must stay on disk, where:

  • access is much slower than in memory, by several orders of magnitude;
  • sequential access (reading or writing consecutive blocks) is much faster than random access.

Quicksort, which accesses elements all over the array, would be extremely slow on disk. External sorting algorithms are designed to minimize the number of passes over the data and to access it sequentially. They are based on the principle of divide and conquer, using the same basic principles as internal algorithms (especially merging):

  1. Generate sorted runs: read the file in chunks that fit in memory, sort each chunk with an internal algorithm, and write it back to disk as a sorted run.
  2. Merge the runs: merge the sorted runs, reading them sequentially, into longer and longer runs, until a single sorted file remains. Merging many runs at once (a kk-way merge, using a priority queue to find the smallest current element among the kk runs) reduces the number of passes.

There are several classic variants of the merging phase: direct merge (runs of fixed, doubling length), natural merge (takes advantage of the runs already present in the data), balanced merge (distributes the runs evenly among several files) and polyphase merge (distributes the runs unevenly to reduce the number of files needed). The cost of external sorting is measured mainly in the number of passes over the data, since each pass means reading and writing the whole file.


Learn More​

Common mistakes
  • Choosing only by the complexity class. Constants, the initial order, stability and memory also decide.
  • Writing your own sort in a real program. Use the library (Arrays.sort, Collections.sort), which is tuned and tested.
  • Comparing measurements taken at very different sizes or on different data. Use the same inputs for all algorithms.

Summary​

  • The simple algorithms are O(n2)O(n^2) (insertion and bubble with sentinel are linear on sorted data); the efficient ones are O(nlog⁑n)O(n \log n) (Quicksort only on average).
  • Measurements confirm the theory: doubling nn quadruples the time of the simple algorithms and roughly doubles that of the efficient ones. The differences between both families become enormous as nn grows.
  • 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.
  • External sorting handles data that does not fit in memory, by generating sorted runs and merging them with sequential accesses.

Practice​

  • πŸ’» Complete lab session 2. Measure bubble, selection, insertion and Quicksort with sorted, reverse and random data, and check that the times agree with the complexity studied for each case.
  • βš–οΈ Compare with ratios. Using the times of two algorithms with different complexities (for example, insertion sort and Quicksort on random data), compute the ratio of their times for increasing nn. Does it tend to 0 or to infinity? And for two algorithms with the same complexity, such as Mergesort and Quicksort on random data?
  • πŸ§ͺ Partially sorted data. Generate sorted arrays and swap kk random pairs of elements. For k=0,10,1,000,n/2k = 0, 10, 1{,}000, n/2, measure insertion sort, Quicksort and Arrays.sort. Which one benefits most from the existing order?
  • πŸ“¦ Simulate external sorting. Sort a file of 10 million integers using only an array of 1 million elements: generate 10 sorted runs in temporary files and merge them with a kk-way merge. How many times is each element read and written?
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.