Sorting Algorithms Explained: Insertion, Merge, Quicksort
Sorting is the classic first algorithms topic because it shows, in a few lines of code, how the same task can cost wildly different amounts of work. This page walks through three algorithms worth knowing, insertion sort, merge sort and quicksort, then explains why real code should almost always call the language's built-in sort. Implementations are in Python 3.10 or later; the built-in examples also show Java 17 or later and JavaScript in Node.js 22 or later or a current browser.
Big O in one paragraph
Big O notation describes how an algorithm's work grows with the input size n, ignoring constant factors. O(n²) means doubling the input roughly quadruples the work; O(n log n) means doubling it slightly more than doubles the work. For a million items, n² is a trillion, while n log₂ n is about twenty million. Any sort that works only by comparing pairs of items needs on the order of n log n comparisons in the worst case, so O(n log n) is the best a general-purpose comparison sort can do.
Insertion sort
Insertion sort works the way many people sort a hand of cards: take the next item and slide it left until it sits after a smaller one.
def insertion_sort(items):
"""Sort a list in place and return it. O(n^2) worst case."""
for i in range(1, len(items)):
current = items[i]
j = i - 1
# Shift larger items one place right to open a gap for current.
while j >= 0 and items[j] > current:
items[j + 1] = items[j]
j -= 1
items[j + 1] = current
return items
if __name__ == "__main__":
print(insertion_sort([5, 2, 9, 1, 5, 6]))
Output: [1, 2, 5, 5, 6, 9]
- Time: O(n²) in the worst and average case (reverse-sorted input is the worst). O(n) when the input is already sorted, because each item moves zero places.
- Space: O(1) extra; it sorts in place.
- Stable: yes. The
>comparison stops at equal items, so they keep their order. - Where it shines: very small or nearly sorted inputs. Fast library sorts switch to it for short runs for exactly that reason.
Merge sort
Merge sort is divide and conquer: split the list in half, sort each half recursively, then merge the two sorted halves by repeatedly taking the smaller front item.
def merge_sort(items):
"""Return a new sorted list. O(n log n) time, O(n) extra space."""
if len(items) <= 1:
return list(items)
middle = len(items) // 2
left = merge_sort(items[:middle])
right = merge_sort(items[middle:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps equal items in order (stable)
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
if __name__ == "__main__":
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
Output: [3, 9, 10, 27, 38, 43, 82]
- Time: O(n log n) in every case. The list is halved about log₂ n times, and each level of merging touches all n items.
- Space: O(n) extra for the merged lists.
- Stable: yes, because the merge takes from the left half when items are equal (
<=). Change it to<and stability is lost. - Where it shines: when you need guaranteed O(n log n) and stability, and for data too big for memory (merging sorted chunks from disk).
Quicksort
Quicksort picks a pivot, partitions the list so that smaller items come before it and the rest after, then sorts each side.
import random
def quicksort(items, lo=0, hi=None):
"""Sort a list in place. Average O(n log n), worst case O(n^2)."""
if hi is None:
hi = len(items) - 1
while lo < hi:
p = partition(items, lo, hi)
# Recurse into the smaller side and loop on the larger one,
# which keeps the recursion depth at O(log n).
if p - lo < hi - p:
quicksort(items, lo, p - 1)
lo = p + 1
else:
quicksort(items, p + 1, hi)
hi = p - 1
return items
def partition(items, lo, hi):
pivot_index = random.randint(lo, hi) # random pivot avoids the sorted-input trap
items[pivot_index], items[hi] = items[hi], items[pivot_index]
pivot = items[hi]
store = lo
for i in range(lo, hi):
if items[i] < pivot:
items[i], items[store] = items[store], items[i]
store += 1
items[store], items[hi] = items[hi], items[store]
return store
if __name__ == "__main__":
print(quicksort([3, 6, 8, 10, 1, 2, 1]))
Output: [1, 1, 2, 3, 6, 8, 10]
- Time: O(n log n) on average, O(n²) in the worst case, when each pivot splits the list very unevenly.
- Space: sorts in place. Recursing into the smaller side and looping on the larger keeps the call depth at O(log n); a naive version can recurse n levels deep and run out of stack on large inputs, the problem described in what exit code 0xC00000FD means.
- Stable: no. Partitioning swaps items across long distances.
- The pivot matters: always choosing the first or last item turns already-sorted input into the worst case. A random pivot makes that unlikely. This simple version is still slow when the list has very many equal items; production versions use three-way partitioning (less than, equal to, greater than the pivot) to handle duplicates.
Testing a sort
A sort is easy to get almost right. Compare it with a trusted one on many random inputs, including the edge cases: empty, one item, duplicates, already sorted and all equal. Save the three files above as insertion_sort.py, merge_sort.py and quicksort.py in the same folder as this test:
import random
from insertion_sort import insertion_sort
from merge_sort import merge_sort
from quicksort import quicksort
for trial in range(500):
data = [random.randint(-50, 50) for _ in range(random.randint(0, 60))]
expected = sorted(data)
assert insertion_sort(list(data)) == expected
assert merge_sort(data) == expected
assert quicksort(list(data)) == expected
assert quicksort(list(range(5000))) == list(range(5000)) # sorted input
assert quicksort([7] * 3000) == [7] * 3000 # all equal
print("all sorts agree with sorted()")
all sorts agree with sorted()
The comparison
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Insertion sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort (random pivot) | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
Bubble sort and selection sort are also O(n²) and appear in many courses; they are worth reading once and not worth using.
What stability means and why you care
A stable sort keeps items that compare equal in their original order. That lets you sort by several keys in passes: sort by the secondary key first, then by the primary key.
orders = [("alice", "2026-03-02"), ("bob", "2026-03-01"),
("alice", "2026-03-01"), ("bob", "2026-02-28")]
orders.sort(key=lambda o: o[1]) # first by date
orders.sort(key=lambda o: o[0]) # then by customer; dates stay in order
for o in orders:
print(o)
Output:
('alice', '2026-03-01')
('alice', '2026-03-02')
('bob', '2026-02-28')
('bob', '2026-03-01')
Each customer's orders stay in date order because the second sort is stable.
In real code, use the built-in sort
The standard library sorts are carefully tuned and thoroughly tested, and they handle edge cases these teaching versions do not. Write your own sort to learn, not to ship.
Python
people = [("Grace", 85), ("Ada", 36), ("Linus", 21), ("Alan", 41)]
by_age = sorted(people, key=lambda p: p[1]) # new list
print(by_age)
people.sort(key=lambda p: p[1], reverse=True) # in place
print(people)
words = ["banana", "apple", "Cherry"]
print(sorted(words)) # uppercase sorts before lowercase
print(sorted(words, key=str.casefold)) # case-insensitive
Output:
[('Linus', 21), ('Ada', 36), ('Alan', 41), ('Grace', 85)]
[('Grace', 85), ('Alan', 41), ('Ada', 36), ('Linus', 21)]
['Cherry', 'apple', 'banana']
['apple', 'banana', 'Cherry']
sorted() returns a new list and works on any iterable; list.sort() sorts in place and returns None. Both are guaranteed stable and adaptive (close to O(n) on nearly sorted data), and both take a key function, which is computed once per item. Plain string sorting is by code point, so uppercase letters come before lowercase; pass key=str.casefold for a case-insensitive order. The Python Sorting Techniques guide covers keys and multi-level sorts in depth.
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SortDemo {
record Person(String name, int age) {}
public static void main(String[] args) {
int[] nums = {5, 2, 9, 1};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
List<Person> people = new ArrayList<>(List.of(
new Person("Grace", 85),
new Person("Ada", 36),
new Person("Linus", 21)));
people.sort(Comparator.comparingInt(Person::age));
System.out.println(people);
}
}
Expected output:
[1, 2, 5, 9]
[Person[name=Linus, age=21], Person[name=Ada, age=36], Person[name=Grace, age=85]]
According to the Java SE documentation, Arrays.sort on primitive arrays uses a dual-pivot quicksort, while sorting objects (Arrays.sort(Object[]), List.sort, Collections.sort) uses a stable, adaptive merge sort. List.of(...) returns an unmodifiable list, which is why the example copies it into an ArrayList before sorting; sorting it directly throws UnsupportedOperationException.
JavaScript
const people = [
{ name: "Grace", age: 85 },
{ name: "Ada", age: 36 },
{ name: "Linus", age: 21 },
];
people.sort((a, b) => a.age - b.age);
console.log(people.map((p) => p.name).join(", "));
console.log([10, 1, 5].sort()); // default compares as strings
console.log([10, 1, 5].sort((a, b) => a - b));
Output:
Linus, Ada, Grace
[ 1, 10, 5 ]
[ 1, 5, 10 ]
Array.prototype.sort is stable in current engines, but with no comparator it converts items to strings, so 10 sorts before 5. Always pass a comparator for numbers.
Picking an approach
- Default: the built-in sort with a
keyor comparator. - Need only the smallest or largest k items?
heapq.nsmallest(k, items)avoids sorting everything. - Searching the same data many times? Sort once, then use binary search (
bisectin Python,Arrays.binarySearchin Java), or put it in a set or dict as described in Python data structures explained.