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.
- Start. The first item on its own is always sorted: [5] | 2, 4, 1. The sorted part has one item.
- 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.
- 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.
- 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 ways (the factorial of n) to arrange n distinct items. For four items that is 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
For n = 4 this is , 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 outcomes. To tell the n! orders apart, it needs , so
Here is the base-2 logarithm. For n = 4, is about 4.58, so at least 5 comparisons are needed. For n = 10, and of that is about 21.8, so at least 22 comparisons are needed. The lower limit grows like . 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.
- n(n-1)/2, insertion sort worst case
- n log2 n, the lower limit's growth
Worked examples
Sort the list 3, 1, 2 with insertion sort.
- Sorted part: [3]. Unsorted: 1, 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.
- 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.
- The formula also gives 3, the worst case for three items.
Interpretation: three items took three comparisons, and the list is in order.
Use the same method on two lists of five: 1, 2, 3, 4, 5 and 5, 4, 3, 2, 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.
- 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.
- The reversed case is the worst case, and it matches .
- 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.
A service must sort 1,000,000 customer records by name. Compare two methods using a rough count of comparisons.
- Insertion sort, worst case: , which is about 500 billion comparisons.
- Merge sort, roughly , which is about 20 million comparisons.
- Divide the two counts: . Insertion sort does roughly 25,000 times as many comparisons.
- 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.
- 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: 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 , 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 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 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 checks, and Greedy Algorithm, which often begins by sorting its choices.