I Implemented Every Sorting Algorithm in Python — And Python's Built-in Sort Crushed Them All
Source: Dev.to
Benchmark Results
| Algorithm | 100 elements | 1,000 elements | 5,000 elements | Practical Limit |
|---|---|---|---|---|
| Bubble Sort | 0.001 s | 0.15 s | 3.2 s | ~500 elements |
| Selection Sort | 0.001 s | 0.13 s | 2.8 s | ~500 elements |
| Insertion Sort | 0.0005 s | 0.08 s | 1.9 s | ~1,000 (great on nearly‑sorted!) |
| Merge Sort | 0.002 s | 0.025 s | 0.14 s | Usable but slow |
| Quick Sort | 0.002 s | 0.021 s | 0.11 s | Usable but recursion hurts |
| Heap Sort | 0.002 s | 0.029 s | 0.16 s | Reliable but never wins |
sorted() (Timsort) | 0.0003 s | 0.0045 s | 0.025 s | Use this always |
Key Takeaways
- Insertion sort beats Merge/Quick on very small inputs; Python’s function calls are costly: they involve method dispatch and type checks, not a single CPU instruction.
- Recursion overhead makes Quick sort’s function calls expensive.
- Memory allocations: Merge sort creates thousands of temporary lists, leading to GC pauses.
- Timsort is a hybrid genius: it detects runs, uses insertion sort for small chunks, and merges adaptively, all in optimized C.
Insertion Sort Example
def insertion_sort(arr):
"""Return a sorted copy of *arr* using insertion sort."""
arr = arr.copy()
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
Never implement your own sort in production Python.
Usesorted()orlist.sort()— they’re faster, stable, and battle‑tested. Write your own only for learning purposes or rare edge cases.
Further Resources
- Detailed explanations – (link to the full article)
- All source code – (link to the repository)
- Benchmark script – (link to the script)
- Raw benchmark data – (link to the data)
External Links
- Full blog post:
- GitHub repository:
What surprised you most about Python’s sorting performance?
Feel free to share your thoughts in the comments.