---
title: Sorting Algorithms Explained: Types, Complexity and Code
url: https://www.masaischool.com/resources/sorting-algorithms-explained
description: Sorting algorithms compared: bubble, insertion, selection, merge, quick, heap and Timsort. Time and space table, tested Python code and which sort is fastest.
updated: 2026-11-25
publisher: Masai (https://www.masaischool.com)
---

# Sorting Algorithms Explained: Types, Time Complexity, Python Code and Which One Is Fastest

> **Short answer**
>
> A sorting algorithm puts items in order. Bubble, insertion and selection sort are simple and take O(n^2) time. Merge sort, quicksort and heapsort take O(n log n). No single one is fastest everywhere: quicksort is quick on random data, and Timsort, a stable merge and insertion hybrid used by Python and by V8 for JavaScript, wins on partly sorted data.

This page is for students learning DSA (data structures and algorithms) and for anyone revising sorting before a coding interview. It compares the algorithms you are expected to know, shows short implementations, and then measures them instead of only quoting Big O.

Every code block was run on Python 3.9.6 or Node.js 24.15.0 on 25 November 2026 and the output shown is the real output. Complexity figures were checked against Wikipedia's sorting algorithm table, and the claims about built-in sorts against the Python documentation, CPython's listsort.txt, the V8 blog and the ECMAScript specification on the same date. If Big O is new to you, read [time complexity and Big O explained](https://www.masaischool.com/resources/time-complexity-and-big-o-explained) first.

1. **Small or nearly sorted** - insertion sort
2. **General purpose** - the built-in sort (Timsort)
3. **Tight memory** - heapsort or in-place quicksort
4. **Small integer keys** - counting or radix sort
A quick guide to choosing a sort. The built-in one is right most of the time.

## Types of sorting algorithms

Sorting means arranging items by a key: marks from high to low, names from A to Z, orders by date. It matters because sorted data makes other work cheap: binary search, finding duplicates, merging two lists and picking the top k all become simple once the data is ordered. Four properties are used to classify sorting algorithms:

| Property | Meaning | Examples |
|---|---|---|
| Comparison or non-comparison | Comparison sorts only ask "is a before b?". Non-comparison sorts use the digits or values of the keys | Merge sort compares. Counting sort and radix sort do not |
| Stable or unstable | A stable sort keeps items with equal keys in their original order | Merge sort and insertion sort are stable. Quicksort and heapsort are not |
| In-place or not | In-place sorts need only a small, fixed amount of extra memory | Heapsort is in-place. Merge sort needs an O(n) buffer |
| Adaptive or not | An adaptive sort does less work when the input is already partly sorted | Insertion sort and Timsort are adaptive. Selection sort is not |

Sorts are also grouped by method: exchanging (bubble sort, quicksort), insertion (insertion sort), selection (selection sort, heapsort) and merging (merge sort). Internal sorting works on data in memory. External sorting handles data too large for memory by sorting chunks and merging them from disk.

## Sorting algorithms compared: time, space and stability

| Algorithm | Best | Average | Worst | Extra space | Stable? |
|---|---|---|---|---|---|
| Bubble sort | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Selection sort | O(n^2) | O(n^2) | O(n^2) | O(1) | No |
| Insertion sort | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quicksort | O(n log n) | O(n log n) | O(n^2) | O(log n) | No |
| Heapsort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Timsort | O(n) | O(n log n) | O(n log n) | O(n) | Yes |
| Counting sort (keys in a range of size r) | O(n + r) | O(n + r) | O(n + r) | O(n + r) | Yes |

These figures match the comparison table on [Wikipedia's sorting algorithm page](https://en.wikipedia.org/wiki/Sorting_algorithm), read on 25 November 2026. Bubble sort's O(n) best case assumes the early-exit check shown below. The same page notes that a comparison sort cannot do better than O(n log n) on average, which is why counting sort and radix sort, which do not compare, are the only ones that can beat it, and only for keys such as small integers.

## Bubble, insertion, merge and quick sort in Python

### The simple O(n^2) sorts

**Bubble sort** repeatedly swaps neighbours that are out of order, so the largest item "bubbles" to the end on each pass. **Insertion sort** grows a sorted section on the left and inserts each new item into its place, the way you sort playing cards in your hand.def bubble_sort(items): a = list(items) for end in range(len(a) - 1, 0, -1): swapped = False for i in range(end): if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i] swapped = True if not swapped: # no swaps in a full pass: already sorted break return a def insertion_sort(items): a = list(items) for i in range(1, len(a)): key = a[i] j = i - 1 while j >= 0 and a[j] > key: # shift bigger items one place right a[j + 1] = a[j] j -= 1 a[j + 1] = key return a marks = [72, 45, 91, 38, 60, 45, 83] print(bubble_sort(marks)) print(insertion_sort(marks))[38, 45, 45, 60, 72, 83, 91] [38, 45, 45, 60, 72, 83, 91]

### The O(n log n) sorts

**Merge sort** splits the list in half, sorts each half by [recursion](https://www.masaischool.com/resources/what-is-recursion) and merges the two sorted halves. **Quicksort** picks a pivot, moves smaller items to its left and larger ones to its right (partitioning), then sorts each side. Both are divide-and-conquer algorithms.def merge_sort(a): if len(a) <= 1: return a mid = len(a) // 2 left, right = merge_sort(a[:mid]), merge_sort(a[mid:]) out, i, j = [], 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: # <= keeps equal items in order: stable out.append(left[i]); i += 1 else: out.append(right[j]); j += 1 return out + left[i:] + right[j:] def quick_sort(a, lo=0, hi=None): # in place, Lomuto partition if hi is None: hi = len(a) - 1 if lo < hi: mid = (lo + hi) // 2 a[mid], a[hi] = a[hi], a[mid] # middle item as pivot, moved to the end pivot, p = a[hi], lo for i in range(lo, hi): if a[i] < pivot: a[i], a[p] = a[p], a[i] p += 1 a[p], a[hi] = a[hi], a[p] # pivot lands in its final place quick_sort(a, lo, p - 1) quick_sort(a, p + 1, hi) return a marks = [72, 45, 91, 38, 60, 45, 83] print(merge_sort(marks)) print(quick_sort(list(marks))) print(merge_sort(marks) == quick_sort(list(marks)) == sorted(marks))[38, 45, 45, 60, 72, 83, 91] [38, 45, 45, 60, 72, 83, 91] True

The other two worth knowing by idea: **selection sort** finds the smallest remaining item and swaps it into place, always making about n^2/2 comparisons. **Heapsort** builds a binary heap, a kind of [tree](https://www.masaischool.com/resources/tree-data-structure-explained) stored in an array, and repeatedly removes the largest item.

## Bubble sort vs merge sort vs quick sort: which is fastest?

Big O hides a lot, so here is a measurement. The script counts comparisons made by each algorithm on 2,000 items in three arrangements: shuffled, already sorted and reversed. The last row wraps each item in a class that counts how many comparisons Python's built-in sorted() makes.import random def bubble(a): a, c = list(a), 0 for end in range(len(a) - 1, 0, -1): swapped = False for i in range(end): c += 1 if a[i] > a[i + 1]: a[i], a[i + 1] = a[i + 1], a[i]; swapped = True if not swapped: break return c def insertion(a): a, c = list(a), 0 for i in range(1, len(a)): key, j = a[i], i - 1 while j >= 0: c += 1 if a[j] <= key: break a[j + 1] = a[j]; j -= 1 a[j + 1] = key return c def merge(a): if len(a) <= 1: return a, 0 mid = len(a) // 2 (l, c1), (r, c2) = merge(a[:mid]), merge(a[mid:]) out, i, j, c = [], 0, 0, c1 + c2 while i < len(l) and j < len(r): c += 1 if l[i] <= r[j]: out.append(l[i]); i += 1 else: out.append(r[j]); j += 1 return out + l[i:] + r[j:], c def quick_last_pivot(a): # naive pivot choice, iterative a, c, stack = list(a), 0, [(0, len(a) - 1)] while stack: lo, hi = stack.pop() if lo >= hi: continue pivot, p = a[hi], lo for i in range(lo, hi): c += 1 if a[i] < pivot: a[i], a[p] = a[p], a[i]; p += 1 a[p], a[hi] = a[hi], a[p] stack += [(lo, p - 1), (p + 1, hi)] return c class Counted: # counts the comparisons sorted() makes n = 0 def __init__(self, v): self.v = v def __lt__(self, other): Counted.n += 1 return self.v < other.v def builtin(a): Counted.n = 0 sorted(Counted(x) for x in a) return Counted.n random.seed(7) n = 2000 shuffled = random.sample(range(n), n) inputs = {"random": shuffled, "sorted": list(range(n)), "reversed": list(range(n, 0, -1))} print(f"{'comparisons, n=2000':<22}" + "".join(f"{k:>10}" for k in inputs)) for name, fn in [("bubble sort", bubble), ("insertion sort", insertion), ("merge sort", lambda a: merge(a)[1]), ("quick sort, last pivot", quick_last_pivot), ("sorted() built-in", builtin)]: print(f"{name:<22}" + "".join(f"{fn(a):>10}" for a in inputs.values()))comparisons, n=2000 random sorted reversed bubble sort 1998847 1999 1999000 insertion sort 1000161 1999 1999000 merge sort 19394 10864 11088 quick sort, last pivot 26207 1999000 1999000 sorted() built-in 19250 1999 1999

- **On random data**, the O(n^2) sorts make 1 to 2 million comparisons. Merge sort, quicksort and the built-in sort make about 19,000 to 26,000, roughly 50 to 100 times fewer.
- **Insertion sort beats bubble sort** on random data, with about half the comparisons (1,000,161 against 1,998,847). Both drop to 1,999 on sorted input.
- **Quicksort with a poor pivot collapses.** Taking the last item as pivot on sorted or reversed input gives 1,999,000 comparisons, the O(n^2) worst case. Real implementations pick a random or median-of-three pivot to avoid this.
- **Merge sort never has a bad day**: between 10,864 and 19,394 comparisons whatever the order.
- **The built-in sort is adaptive.** On sorted and on reversed input it needs only 1,999 comparisons, which is n - 1, because it detects the existing run.

So which sorting algorithm is fastest? On random data in memory, a well-built quicksort is usually the fastest in wall-clock time because it sorts in place. Merge sort gives the same O(n log n) with a guarantee and stability, at the cost of extra memory. On real-world data that is often partly ordered, Timsort wins. These are comparison counts on one machine-independent test, not timings, and the random column depends on the seed and Python version.

## What Python's sorted() and JavaScript's sort() actually use

### Python

The [Python sorting guide](https://docs.python.org/3/howto/sorting.html) names the algorithm: Timsort, which takes advantage of any order already present in the data. CPython's own design note, [listsort.txt](https://github.com/python/cpython/blob/main/Objects/listsort.txt), describes it as an adaptive, stable, natural mergesort. It finds runs that are already ordered, extends short runs with insertion sort and merges runs. Since Python 3.11 the order in which runs are merged follows the powersort strategy, per the 3.11.0 alpha 1 changelog. The docs guarantee that sorted() and list.sort() are stable.students = [("Asha", "CSE", 81), ("Ravi", "ECE", 74), ("Meena", "CSE", 74), ("Kabir", "ECE", 81), ("Divya", "CSE", 90)] by_marks = sorted(students, key=lambda s: s[2], reverse=True) print([s[0] for s in by_marks]) # two passes: sort by the minor key first, then by the major key by_branch_then_marks = sorted(by_marks, key=lambda s: s[1]) print([(s[1], s[0], s[2]) for s in by_branch_then_marks])['Divya', 'Asha', 'Kabir', 'Ravi', 'Meena'] [('CSE', 'Divya', 90), ('CSE', 'Asha', 81), ('CSE', 'Meena', 74), ('ECE', 'Kabir', 81), ('ECE', 'Ravi', 74)]

Stability is what makes the two-pass trick work: after sorting by branch, students within each branch are still in marks order.

### JavaScript

The ECMAScript specification does not name an algorithm. It only requires the result to be correctly ordered and, in its current text, that the sort is stable. Each engine chooses. The V8 team's post [Getting things sorted in V8](https://v8.dev/blog/array-sort) explains that V8, the engine in Chrome and Node.js, moved from a quicksort-based implementation to Timsort in V8 7.0 (Chrome 70), which made Array.prototype.sort stable there. A stable sort became a specification requirement in ES2019, as V8's [stable sort note](https://v8.dev/features/stable-sort) records.const nums = [100, 25, 9, 1]; console.log([...nums].sort()); // default: compares as strings console.log([...nums].sort((a, b) => a - b)); // numeric comparator const students = [ { name: "Asha", marks: 81 }, { name: "Ravi", marks: 74 }, { name: "Meena", marks: 74 }, { name: "Kabir", marks: 81 }, ]; const ranked = students.toSorted((a, b) => b.marks - a.marks); console.log(ranked.map((s) => s.name).join(", ")); // ties keep input order console.log(students[0].name); // toSorted left the original alone[ 1, 100, 25, 9 ] [ 1, 9, 25, 100 ] Asha, Kabir, Ravi, Meena Asha

The first line is the classic trap: with no comparator, JavaScript converts items to strings, so 100 sorts before 25. Always pass (a, b) => a - b for numbers. sort() changes the array in place, and toSorted() returns a sorted copy. For more JavaScript practice, try the [JavaScript practice projects](https://www.masaischool.com/resources/projects/javascript-practice-projects).

## When to use which, and interview questions

| Situation | Use | Why |
|---|---|---|
| Day-to-day code | The built-in sort with a key or comparator | Tested, stable and O(n log n). Writing your own is rarely justified |
| Fewer than a few dozen items, or nearly sorted data | Insertion sort | Low overhead and O(n) when almost in order. Hybrid library sorts use it for short runs |
| Equal keys must keep their order | Merge sort or Timsort | Both are stable |
| Memory is tight | Heapsort, or in-place quicksort | O(1) and O(log n) extra space |
| Guaranteed worst case needed | Merge sort or heapsort | Always O(n log n). Quicksort can degrade to O(n^2) |
| Linked list | Merge sort | Merging needs no random access. See [linked list explained](https://www.masaischool.com/resources/linked-list-explained) |
| Integers in a small known range | Counting sort or radix sort | O(n + r), not limited by the comparison bound |
| Only the top k items needed | A heap, not a full sort | O(n log k) instead of O(n log n) |

### Sorting questions asked in interviews

- **Why is quicksort often preferred over merge sort for arrays?** It sorts in place with O(log n) stack space and has good cache behaviour. Merge sort needs an O(n) buffer.
- **When does quicksort hit O(n^2)?** When the pivot is always the smallest or largest item, as with a first or last pivot on sorted input. The table above shows it.
- **What is a stable sort and when does it matter?** Equal keys keep their input order. It matters when you sort records by one field after another.
- **Which sort would you use for a nearly sorted array?** Insertion sort, or the built-in Timsort, both O(n) in that case.
- **Can you sort faster than O(n log n)?** Not by comparisons alone. Counting and radix sort can, for restricted keys.
- **How would you sort a file larger than memory?** External merge sort: sort chunks that fit, write them out, then merge the chunks.
- **Find the kth largest element.** Use a min-heap of size k, or quickselect, which is O(n) on average.

More practice problems, grouped by pattern, are in the [DSA interview questions](https://www.masaischool.com/resources/dsa-interview-questions), and the full topic order is in the [data structures and algorithms path](https://www.masaischool.com/resources/data-structures-and-algorithms).

## Frequently asked questions

### What are the types of sorting algorithms?

The main ones are bubble sort, selection sort, insertion sort, merge sort, quicksort and heapsort, which all work by comparing items, and counting sort and radix sort, which do not. They are also classified as stable or unstable, in-place or not, and adaptive or not.

### Which sorting algorithm is the fastest?

It depends on the data. Quicksort is usually fastest on random data in memory. Timsort, used by Python and by V8 for JavaScript, is fastest on partly sorted data and needs only n - 1 comparisons on sorted input. Counting sort and radix sort can beat both for small integer keys.

### What is the difference between bubble sort, merge sort and quick sort?

Bubble sort swaps neighbours and takes O(n^2) time, so it is for learning only. Merge sort splits, sorts and merges in O(n log n) every time, is stable and needs O(n) extra memory. Quicksort partitions around a pivot, averages O(n log n) in place, but can fall to O(n^2) with bad pivots.

### Which sorting algorithm does Python use?

CPython's sorted() and list.sort() use Timsort, an adaptive, stable hybrid of merge sort and insertion sort written by Tim Peters. It is O(n log n) in the worst case and O(n) on already sorted input. Since Python 3.11 it merges runs using the powersort strategy. The documentation guarantees stability.

### Which sorting algorithm does JavaScript use?

The ECMAScript specification does not fix an algorithm, only that the sort is stable. V8, the engine in Chrome and Node.js, has used Timsort since V8 7.0 (Chrome 70). Other engines choose their own stable algorithm. Without a comparator, items are compared as strings.

### What is a stable sorting algorithm?

A stable sort keeps items that have equal keys in the same relative order as in the input. Bubble sort, insertion sort, merge sort, Timsort and counting sort are stable. Selection sort, quicksort and heapsort are not, in their standard forms. Stability lets you sort by several fields in separate passes.

### Which sorting algorithm is best for interviews?

Know merge sort and quicksort well enough to write from memory, and be able to explain insertion sort and heapsort. Memorise the complexity table and the idea of stability. In problem-solving rounds, use the language's built-in sort and state its cost as O(n log n).

## Sources checked

- [Best, average, worst, memory and stability for each algorithm; comparison-sort lower bound; classification by method](https://en.wikipedia.org/wiki/Sorting_algorithm)
- [Python uses Timsort; sorts are guaranteed stable; multi-pass sorting](https://docs.python.org/3/howto/sorting.html)
- [sorted() is guaranteed to be stable](https://docs.python.org/3/library/functions.html)
- [Timsort described as an adaptive, stable, natural mergesort; as few as N-1 comparisons; powersort merge strategy](https://github.com/python/cpython/blob/main/Objects/listsort.txt)
- [Python 3.11.0 alpha 1: list sorting uses the powersort merge-ordering strategy (bpo-34561)](https://docs.python.org/3/whatsnew/changelog.html)
- [V8 moved Array.prototype.sort from quicksort to Timsort; stable in V8 v7.0 / Chrome 70; O(n) on sorted input, O(n log n) worst case](https://v8.dev/blog/array-sort)
- [Stable Array.prototype.sort is part of ES2019](https://v8.dev/features/stable-sort)
- [SortIndexedProperties: the sort is stable; order is implementation-defined for inconsistent comparators](https://tc39.es/ecma262/multipage/indexed-collections.html)
