📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Data Structures and Algorithms Sorting Algorithms

Sorting Algorithms

5 min read Quiz at the end
Merge sort O(n log n) stable; quick sort fastest in practice; use Python sorted() which is Tim sort.

Sorting Algorithms

AlgorithmBestAverageWorstSpace
Bubble SortO(n)O(n²)O(n²)O(1)
Insertion SortO(n)O(n²)O(n²)O(1)
Merge SortO(n log n)O(n log n)O(n log n)O(n)
Quick SortO(n log n)O(n log n)O(n²)O(log n)
Heap SortO(n log n)O(n log n)O(n log n)O(1)
Counting SortO(n+k)O(n+k)O(n+k)O(k)
Tim Sort (Python)O(n)O(n log n)O(n log n)O(n)
# Merge Sort -- divide and conquer, stable O(n log n)
def merge_sort(arr):
    if len(arr) <= 1: return arr
    mid   = len(arr) // 2
    left  = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)

def merge(left, right):
    result, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]: result.append(left[i]);  i+=1
        else:                    result.append(right[j]); j+=1
    return result + left[i:] + right[j:]

# Quick Sort -- fastest in practice O(n log n) avg
def quick_sort(arr, lo=0, hi=None):
    if hi is None: hi = len(arr)-1
    if lo < hi:
        p = partition(arr, lo, hi)
        quick_sort(arr, lo, p-1)
        quick_sort(arr, p+1, hi)
Topic Quiz · 1 questions

Test your understanding before moving on

1. What is the time complexity of merge sort in all cases?
💡 Merge sort always divides n times (log n) and merges n elements each time — always O(n log n).