Skip to content
Concept ยท Data Structures and Algorithms

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

By Younus FardeenUpdated 25 Nov 202613 min read
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.

On this pageTypes of sorting algorithmsSorting algorithms compared: time, space and stabilityBubble, insertion, merge and quick sort in PythonBubble sort vs merge sort vs quick sort: which is fastest?What Python's sorted() and JavaScript's sort() actually useWhen to use which, and interview questionsFrequently asked questionsSources checked

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 first.

  1. 1Small or nearly sortedinsertion sort
  2. 2General purposethe built-in sort (Timsort)
  3. 3Tight memoryheapsort or in-place quicksort
  4. 4Small integer keyscounting 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:

PropertyMeaningExamples
Comparison or non-comparisonComparison sorts only ask "is a before b?". Non-comparison sorts use the digits or values of the keysMerge sort compares. Counting sort and radix sort do not
Stable or unstableA stable sort keeps items with equal keys in their original orderMerge sort and insertion sort are stable. Quicksort and heapsort are not
In-place or notIn-place sorts need only a small, fixed amount of extra memoryHeapsort is in-place. Merge sort needs an O(n) buffer
Adaptive or notAn adaptive sort does less work when the input is already partly sortedInsertion 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

AlgorithmBestAverageWorstExtra spaceStable?
Bubble sortO(n)O(n^2)O(n^2)O(1)Yes
Selection sortO(n^2)O(n^2)O(n^2)O(1)No
Insertion sortO(n)O(n^2)O(n^2)O(1)Yes
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
QuicksortO(n log n)O(n log n)O(n^2)O(log n)No
HeapsortO(n log n)O(n log n)O(n log n)O(1)No
TimsortO(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, 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 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 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 names the algorithm: Timsort, which takes advantage of any order already present in the data. CPython's own design note, 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 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 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.

When to use which, and interview questions

SituationUseWhy
Day-to-day codeThe built-in sort with a key or comparatorTested, stable and O(n log n). Writing your own is rarely justified
Fewer than a few dozen items, or nearly sorted dataInsertion sortLow overhead and O(n) when almost in order. Hybrid library sorts use it for short runs
Equal keys must keep their orderMerge sort or TimsortBoth are stable
Memory is tightHeapsort, or in-place quicksortO(1) and O(log n) extra space
Guaranteed worst case neededMerge sort or heapsortAlways O(n log n). Quicksort can degrade to O(n^2)
Linked listMerge sortMerging needs no random access. See linked list explained
Integers in a small known rangeCounting sort or radix sortO(n + r), not limited by the comparison bound
Only the top k items neededA heap, not a full sortO(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, and the full topic order is in the data structures and algorithms path.

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

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Time complexity and Big O

Big O classes, rules for loops and recursion, and real step counts in Python

Open →
Interview prep

DSA interview questions

14 patterns with Python code, 40 problems, a six-week plan and company notes

Open →
Explainer

What is recursion?

Base case, call stack and examples, with code in three languages.

Open →