Sorting Algorithms

📖 Introduction

Sorting is one of the most fundamental operations in computer science. When I first started programming, I used to just call .sort() without thinking. But understanding sorting algorithms taught me critical lessons about algorithm design, trade-offs, and why Python's Timsort is so cleverly designed.

Knowing when to use counting sort over quicksort, or understanding why merge sort is preferred for linked lists, has helped me make better decisions in production systems handling millions of records.


📊 Sorting Overview

Comparison-Based vs Non-Comparison

spinner

Key Properties

Property
Description

Stable

Equal elements maintain relative order

In-place

Uses O(1) extra space

Adaptive

Faster for partially sorted data

Algorithm Comparison

Algorithm
Best
Average
Worst
Space
Stable

Bubble

O(n)

O(n²)

O(n²)

O(1)

Selection

O(n²)

O(n²)

O(n²)

O(1)

Insertion

O(n)

O(n²)

O(n²)

O(1)

Merge

O(n log n)

O(n log n)

O(n log n)

O(n)

Quick

O(n log n)

O(n log n)

O(n²)

O(log n)

Heap

O(n log n)

O(n log n)

O(n log n)

O(1)

Counting

O(n+k)

O(n+k)

O(n+k)

O(k)

Radix

O(nk)

O(nk)

O(nk)

O(n+k)


🐢 Simple Sorts O(n²)

Bubble Sort

Selection Sort

Insertion Sort


⚡ Efficient Sorts O(n log n)

Merge Sort

spinner

Quick Sort

Heap Sort


🚀 Linear Time Sorts O(n)

Counting Sort

Radix Sort

Bucket Sort


🐍 Python's Timsort

Python uses Timsort—a hybrid of merge sort and insertion sort.

Timsort Characteristics


📊 Sorting Problems

Sort Colors (Dutch National Flag)

Merge Intervals

Largest Number

Kth Largest Element (QuickSelect)


📝 Practice Exercises

Exercise 1: Sort an Array

chevron-rightSolutionhashtag

Exercise 2: Meeting Rooms II

chevron-rightSolutionhashtag

Exercise 3: Relative Sort Array

chevron-rightSolutionhashtag

🔑 Key Takeaways

  1. Use Python's built-in sort for most cases—Timsort is highly optimized

  2. Merge sort for stability and guaranteed O(n log n)

  3. Quick sort for average-case performance and in-place sorting

  4. Counting/radix sort when data range is limited

  5. Heap sort when memory is constrained

  6. Understand stability when sort order matters


🚀 What's Next?

In the next article, we'll explore searching algorithms:

  • Binary search and its variations

  • Search in rotated arrays

  • Search space problems

  • Lower and upper bounds

Next: Article 11 - Searching


📚 References

  • CLRS Chapters 7-8: Sorting Algorithms

  • Python Timsort implementation (CPython)

  • "The Art of Computer Programming" Vol. 3: Sorting

Last updated