Search

Search papers and lessons

Sorting Algorithm

Level 1 · 11 min read

A sorting algorithm rearranges a list into order using comparisons and moves; the method you pick decides how many comparisons it needs as the list grows.

On this page

  • Colour = topic mix
  • Discrete math
  • Algorithms
  • Calculus
  • ReadReady to readNot yet

TL;DR

A sorting algorithm is a step-by-step method that takes a list of items and rearranges them into order, such as smallest to largest. It works by comparing pairs of items and moving them around. Sorting matters because sorted data makes many later tasks fast, such as finding a value or spotting duplicates. Different methods do the same job with very different amounts of work as the list grows.

Builds on: Array, Big-O Notation · Leads to: Binary Search, Greedy Algorithm

Where it's used

  • Databases. When a query asks for rows in order, such as the newest orders first, the database sorts them. Sorted keys also let it build an index that a lookup can walk, as in Database Index.
  • Shops and spreadsheets. A product page sorted by price, or a spreadsheet column sorted from A to Z, is a sort on a list of records. The user sees the result at once, so the method has to be fast even for a few thousand rows.
  • Preparing data for other steps. To find duplicate customers, or the median value of a column, the easiest route is to sort first. Once the values are in order, duplicates sit next to each other, and the middle value is in the middle position.

How it works

Take a short list, 5, 2, 4, 1, and sort it with insertion sort. This is a simple method. It keeps the left part of the list sorted. It takes the next unsorted item and slides it left into its place. The sorted part is in brackets below.

  1. Start. The first item on its own is always sorted: [5] | 2, 4, 1. The sorted part has one item.
  2. Take 2. Compare 2 with 5. Since 2 is less than 5, move 5 one place right. The 2 has nowhere left to go, so it goes to the front: [2, 5] | 4, 1. That was 1 comparison. Check: the sorted part now has two items, and they are in order.
  3. Take 4. Compare 4 with 5. Since 4 is less, move 5 right. Compare 4 with 2. Since 4 is greater, stop and place 4 after the 2: [2, 4, 5] | 1. That was 2 more comparisons, 3 in total. Check: the sorted part holds the same items as before, plus 4, and is still in order.
  4. Take 1. Compare 1 with 5, move 5 right. Compare 1 with 4, move 4 right. Compare 1 with 2, move 2 right. Now the 1 is at the front: [1, 2, 4, 5]. That was 3 more comparisons, 6 in total. Check: the sorted part is now the whole list.

The list is sorted after 6 comparisons and 5 moves. The method always works this way: take the next item, find its place among the sorted items, and insert it there.

flowchart TD
  A["Sorted part: the first item"] --> B["Take the next item x"]
  B --> C{"Is there a sorted item to the left of x?"}
  C -- no --> F["Put x in this position"]
  C -- yes --> D{"Is that item greater than x?"}
  D -- yes --> E["Move that item one place right"]
  E --> C
  D -- no --> F
  F --> G{"Any unsorted items left?"}
  G -- yes --> B
  G -- no --> H["Done: the whole list is sorted"]

The math

Let n be the number of items. The algorithm's cost is the count of comparisons it makes, and we want to know how that count grows with n. Two facts matter: how many orders are possible, and how many comparisons a method needs for insertion sort in the worst case.

Step 1 in symbols: the possible orders

There are n!=n×(n−1)×⋯×1n! = n \times (n-1) \times \cdots \times 1 ways (the factorial of n) to arrange n distinct items. For four items that is 4!=244! = 24 orders. Sorting means picking the one right order out of all of them.

Step 2 in symbols: insertion sort's count

When insertion sort places item i, the sorted part to its left has i minus 1 items. In the worst case the new item is smaller than all of them and passes each one, which takes at most i minus 1 comparisons. Summing over all items gives

∑i=2n(i−1)=1+2+⋯+(n−1)=n(n−1)2\sum_{i=2}^{n} (i-1) = 1 + 2 + \cdots + (n-1) = \frac{n(n-1)}{2}

For n = 4 this is 4×32=6\frac{4 \times 3}{2} = 6, which matches the trace above. For n = 10 it is 45.

Step 3 in symbols: a lower limit for every comparison sort

A comparison has two possible answers. Draw a comparison method as a decision tree, where each node is a comparison, each branch is one answer, and each leaf is a final order. After k comparisons, the method has been split into at most 2k2^k outcomes. To tell the n! orders apart, it needs 2k≥n!2^k \ge n!, so

k≥log⁡2(n!)k \ge \log_2 (n!)

Here log⁡2\log_2 is the base-2 logarithm. For n = 4, log⁡224\log_2 24 is about 4.58, so at least 5 comparisons are needed. For n = 10, 10!=3,628,80010! = 3{,}628{,}800 and log⁡2\log_2 of that is about 21.8, so at least 22 comparisons are needed. The lower limit grows like nlog⁡2nn \log_2 n. Merge sort, which splits the list in half, sorts each half by the same method (recursively), and merges the two sorted halves, grows at the same rate, which is why they are the usual choice for large lists.

5101520253035400200400600800n, number of itemscomparisons
  • n(n-1)/2, insertion sort worst case
  • n log2 n, the lower limit's growth
The quadratic curve climbs far faster. The points mark n = 4 (6 comparisons) and n = 10 (45 comparisons).

Worked examples

Example
1. Three numbers (tiny)

Sort the list 3, 1, 2 with insertion sort.

  1. Sorted part: [3]. Unsorted: 1, 2.
  2. Take 1. Compare it with 3. Since 1 is less, move 3 right. The 1 is at the front: [1, 3] | 2. That was 1 comparison.
  3. Take 2. Compare it with 3. Since 2 is less, move 3 right. Compare it with 1. Since 2 is greater, stop and place 2 after the 1: [1, 2, 3]. That was 2 more comparisons, 3 in total.
  4. The formula 3×22\frac{3 \times 2}{2} also gives 3, the worst case for three items.

Interpretation: three items took three comparisons, and the list is in order.

Example
2. Five numbers, already sorted and reversed (standard)

Use the same method on two lists of five: 1, 2, 3, 4, 5 and 5, 4, 3, 2, 1.

  1. Sorted list. Taking 2 compares it with 1, and 2 is greater, so it stays put: 1 comparison. Taking 3, 4 and 5 each costs 1 comparison as well. Total: 4 comparisons and no moves.
  2. Reversed list. Taking 4 passes 5: 1 comparison, and it reaches the front. Taking 3 passes 5 and 4: 2 comparisons. Taking 2 costs 3, and taking 1 costs 4. Total: 1 + 2 + 3 + 4 = 10 comparisons, and 10 moves.
  3. The reversed case is the worst case, and it matches 5×42=10\frac{5 \times 4}{2} = 10.
  4. The best case for insertion sort on any list of n items is n minus 1 comparisons, here 4.

Interpretation: the same method on the same five numbers cost 4 comparisons or 10, depending only on the starting order. The method's cost depends on the input, not only on its size.

Example
3. A million customer records (realistic)

A service must sort 1,000,000 customer records by name. Compare two methods using a rough count of comparisons.

  1. Insertion sort, worst case: 1,000,000×999,9992≈5×1011\frac{1{,}000{,}000 \times 999{,}999}{2} \approx 5 \times 10^{11}, which is about 500 billion comparisons.
  2. Merge sort, roughly nlog⁡2n=1,000,000×19.93≈2×107n \log_2 n = 1{,}000{,}000 \times 19.93 \approx 2 \times 10^{7}, which is about 20 million comparisons.
  3. Divide the two counts: 5×1011/2×107≈25,0005 \times 10^{11} / 2 \times 10^{7} \approx 25{,}000. Insertion sort does roughly 25,000 times as many comparisons.
  4. If a machine made a billion comparisons per second, and nothing else took time, insertion sort would need about 500 seconds, and merge sort about 0.02 seconds.
  5. Interpretation: for large lists, the choice of method matters far more than any speed-up of the machine. This is why libraries use the faster methods for big inputs.

Try it: insertion sort is given 100 items in the worst order. How many comparisons does the worst case take?

Answer: 100×992=4,950\frac{100 \times 99}{2} = 4{,}950 comparisons.

Common mistakes and tradeoffs

It is tempting to think there is one correct way to sort. In fact there are many methods, and they differ in how many comparisons they need, how much extra memory they use, and whether they keep equal items in their original order. Choosing one is a trade-off, not a matter of right and wrong.

It is tempting to think that a method with a smaller growth rate, such as nlog⁡2nn \log_2 n, is always faster. In fact for a short list, insertion sort's simple steps are cheap, and its growth rate matters little. This is why many real libraries switch to insertion sort for small pieces of a bigger sort.

It is tempting to think all sorts give the same result. In fact when two records have the same key, a sort may or may not keep them in their original order. A sort that keeps them is called stable. Suppose a list of customers is sorted by city, and two of them live in Leeds. A stable sort keeps them in the order they were in before. An unstable sort may swap them, which surprises anyone who sorted by name first and then by city.

When to use a sort: you need an ordered list to read, to search with Binary Search, or to find duplicates and medians. When not to use one: you only need the smallest item (one scan is enough), or you only need exact lookups (a Hash Table answers those without sorting). Insertion sort is a good choice for small or nearly sorted inputs, and merge sort is a good choice for large inputs when the order of equal items matters.

History

Early punched-card machines in the 1890s sorted cards into bins one column at a time. Business and government data processing grew up around this kind of mechanical sorting. When electronic computers arrived, sorting was one of the first big tasks they took on. John von Neumann described merge sort in 1945. Tony Hoare invented quicksort around 1959 and published it in 1961. Donald Knuth's The Art of Computer Programming, Volume 3, Sorting and Searching, appeared in 1973 and set out the analysis of many methods. Sorting became a standard topic because it is simple to state, its methods differ sharply in cost, and it appears inside so many other programs.

Recap

  • A sorting algorithm rearranges a list into order using comparisons and moves.
  • Insertion sort grows a sorted left part one item at a time, and its worst case is n(n−1)2\frac{n(n-1)}{2} comparisons.
  • Sorted input costs only n minus 1 comparisons for insertion sort, so the input order matters.
  • No method that uses comparisons can beat about nlog⁡2nn \log_2 n in the worst case, and merge sort grows at that rate.
  • Methods also differ in extra memory and in whether they keep equal items in order.

Read next: Binary Search, which needs a sorted list and then finds a value in about log⁡2n\log_2 n checks, and Greedy Algorithm, which often begins by sorting its choices.

Check yourself

QuestionWhat does a sorting algorithm produce from its input?Show answer
A sorting algorithm produces the same items rearranged into order, such as smallest to largest, using comparisons and moves. It does not add or remove items.
QuestionRun insertion sort on 4, 3, 2, 1. How many comparisons does it make in total?Show answer
Taking 3 compares with 4, moves 4, and reaches the front: 1 comparison. Taking 2 compares with 4 and 3, then reaches the front: 2 comparisons. Taking 1 costs 3 comparisons. Total: 1 + 2 + 3 = 6, which equals 4×32\frac{4 \times 3}{2}.
QuestionWhy does the lower limit log⁡2(n!)\log_2(n!) apply to every comparison sort, not only to insertion sort?Show answer
Each comparison has two possible answers, so k comparisons can separate at most 2k2^k outcomes. A sort must tell the n! possible orders apart, so it needs 2k≥n!2^k \ge n!. That argument uses only comparisons and says nothing about how a particular method chooses them, so it holds for every comparison sort.
QuestionA list of 20 records is sorted by city with an unstable sort. Two records, both from Leeds, change places. What property was missing, and what kind of sort keeps their order?Show answer
The missing property is stability. A stable sort keeps items with equal keys in their original order, so choosing a stable sort keeps the two Leeds records as they were.

Sources

Sorting Algorithm — explained simply · ungoon.me