Computer Science · Lesson 13
Sorting Algorithms
From shuffled decks to billions of database records, computers sort data constantly. Bubble sort, merge sort, and quicksort tackle the same problem — "put these in order" — in radically different ways, with enormous consequences for speed.
Who Was Donald Knuth?
Donald Knuth (1938–present) is an American computer scientist and mathematician at Stanford University, often called the "father of algorithm analysis." His multi-volume masterwork The Art of Computer Programming — begun in 1962 and still being written — is the most comprehensive treatment of algorithms ever compiled. Knuth formalized Big-O notation as a rigorous language for describing how algorithms scale, and his painstaking analysis of sorting algorithms established the mathematical foundations that every computer scientist still uses today. He also created the TeX typesetting system and famously offers a $2.56 reward for any error found in his books.
Big-O Complexity — How Fast Is "Fast"?
Big-O notation describes how an algorithm's time (or space) grows as input size n increases. It captures the worst-case growth rate, ignoring constants.
The difference between O(n²) and O(n log n) sounds abstract — until n = one billion database records, and the difference is hours vs. seconds.
| Algorithm | Best Case | Average | Worst Case | Notes |
|---|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | Simple but slow; only good for nearly-sorted data |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | Always fast; divide and conquer; stable |
| Quicksort | O(n log n) | O(n log n) | O(n²) | Very fast in practice; worst case rare with good pivot |
Sorting Visualiser
Select an algorithm and click Start. Bars being compared are shown in orange; sorted bars turn green. Use the panel controls to change algorithm, speed, and array size.
Real-World Applications
Practice Problems
Easy1. Bubble sort works by comparing and possibly swapping adjacent elements. True or False?
Easy2. How many comparisons does bubble sort need in the worst case for n = 4? (Worst case = n × (n−1) / 2)
Medium3. Merge sort splits an array in half repeatedly. For an array of 8 elements, how many levels of splitting occur before you reach single-element subarrays? (log₂ 8 = ?)
Medium4. Quicksort's worst case happens when the chosen pivot is always the smallest or largest element. What is that time complexity?
Challenge5. An array of 1,024 items is sorted with merge sort. Merge sort needs approximately n · log₂(n) comparisons. How many comparisons is that? (log₂ 1024 = 10)