Sub topic 1
Divide and Conquer: The Idea Behind Quicksort
Quicksort is one of the most widely used sorting algorithms. Its core idea is short: pick one element, put everything smaller on one side and everything larger on the other, then sort each side the same way. This chapter covers that idea using the general strategy of divide and conquer. Later chapters replace the simple code here with an efficient in-place version and analyze how fast it runs.
Prerequisites
This chapter assumes you are comfortable with:
- Basic programming in Python or a similar language, including list comprehensions.
- Arrays (Python lists) and index-based access such as
xs[i]. - Recursion and the call stack: a function calling itself, and why it needs a base case.
- Big-O notation at the level of "O(n) means work grows linearly with input size."
- At least one simple sorting algorithm, such as insertion sort.
You do not need to know merge sort, but it helps as a point of comparison.
The Divide-and-Conquer Pattern
Divide and conquer is a way of designing algorithms. A problem is solved in three steps:
- Divide the problem into smaller subproblems of the same kind.
- Conquer each subproblem by solving it recursively. Subproblems small enough to be trivial are solved directly. These are the base cases.
- Combine the subproblem solutions into a solution for the original problem.
The pattern works when two conditions hold. Each subproblem must be strictly smaller than the original, so the recursion ends. The combine step must also be cheap compared with solving the whole problem directly.
Sorting suits this pattern well. A list of zero or one elements is already sorted, which gives a natural base case. The open question is how to split a list so that sorted pieces can be put back together easily.
Two Ways to Split a Sorting Problem
There are two classic answers, and they put the hard work in opposite places.
Merge sort splits the list by position: the first half and the second half. Splitting is trivial. The halves have no relationship to each other, though, so the combine step has to merge two sorted lists by comparing elements one at a time.
Quicksort splits the list by value. It picks an element called the pivot. Every element less than the pivot goes into one group and every element greater goes into another. This split takes real work, since every element has to be compared with the pivot. In return, combining is trivial: every element in the "less" group belongs before every element in the "greater" group, so the sorted result is just the sorted left group, then the pivot, then the sorted right group.
| Aspect | Merge sort | Quicksort |
|---|---|---|
| How the list is divided | By position (halves) | By value (relative to a pivot) |
| Cost of dividing | Constant (compute a midpoint) | Linear (compare each element to the pivot) |
| Cost of combining | Linear (merge two sorted lists) | Constant in concept (concatenate) |
| Are subproblem sizes guaranteed equal? | Yes | No, they depend on the pivot |
The last row matters most for the rest of this tutorial. Merge sort always splits evenly. Quicksort's split is only as good as its pivot. A pivot near the median gives two halves of about equal size. A pivot near the minimum or maximum gives one empty side and one side almost as big as the original. Most of the engineering in later chapters deals with this weakness.
A First Quicksort
The version below is the clearest way to see the structure. It is not the version you would use in production, because it builds new lists instead of rearranging the original, but every quicksort keeps this shape.
def quicksort_simple(xs):
if len(xs) <= 1:
return xs
pivot = xs[len(xs) // 2]
less = [x for x in xs if x < pivot]
equal = [x for x in xs if x == pivot]
greater = [x for x in xs if x > pivot]
return quicksort_simple(less) + equal + quicksort_simple(greater)
print(quicksort_simple([5, 3, 8, 1, 9, 2, 5])) # [1, 2, 3, 5, 5, 8, 9]Here is how the code maps onto the three steps:
- Base case:
len(xs) <= 1returns the list unchanged. This covers both the empty list and single-element lists. - Divide: the pivot is the middle element. The three comprehensions sort every element into
less,equal, orgreater. - Conquer: the function calls itself on
lessandgreater. Theequallist is already sorted, because all of its elements are the same value. - Combine: list concatenation with
+.
Why it always terminates
The equal list always contains at least the pivot itself. So less and greater each have at most len(xs) - 1 elements, and every recursive call works on a strictly smaller list. The sizes keep shrinking until they reach the base case. That guarantee is the first condition of divide and conquer, and it depends on keeping the pivot out of both recursive calls.
Watching the Recursion
Adding one print statement shows the recursion as a tree. Indentation shows depth.
def quicksort_traced(xs, depth=0):
print(" " * depth + str(xs))
if len(xs) <= 1:
return xs
pivot = xs[len(xs) // 2]
less = [x for x in xs if x < pivot]
equal = [x for x in xs if x == pivot]
greater = [x for x in xs if x > pivot]
return (quicksort_traced(less, depth + 1)
+ equal
+ quicksort_traced(greater, depth + 1))
print(quicksort_traced([7, 2, 9, 4, 1, 8, 3]))Output:
[7, 2, 9, 4, 1, 8, 3]
[2, 1, 3]
[]
[2, 3]
[2]
[]
[7, 9, 8]
[7, 8]
[7]
[]
[]
[1, 2, 3, 4, 7, 8, 9]The first pivot is 4, which happens to be the median. It splits seven elements into two groups of three. The next pivots are 1 and 9, the extremes of their groups, so those splits are lopsided. Each produces an empty side.
Two facts about this tree carry into the complexity analysis later:
- At every depth, the sublists together hold at most
nelements, so the divide work per level is O(n). - The total cost therefore depends on how many levels there are. Balanced splits give about log₂ n levels. Lopsided splits give up to n levels.
Try the tutorial's original input, [5, 3, 8, 1, 9, 2, 5], with the traced version. The middle-element pivots turn out to be 1, 9, 8, 2, 3, and then 5. Nearly every split peels off a single element, and the tree goes six levels deep for seven elements. The same code with the same pivot rule can produce a well-balanced tree or a degenerate one, depending only on the input.
Common Errors
Other mistakes that come up often:
- Wrong base case. Checking only
len(xs) == 1makes the function returnNonefor an empty list, because no branch returns. The comprehensions produce empty lists all the time, so<= 1is required. - Combining in the wrong order. Writing
greater + equal + lessgives descending order. The combine step is where the ordering guarantee lives. - Assuming a middle-index pivot is a middle-value pivot.
xs[len(xs) // 2]is the element at the middle position. Its value can be anything, as the trace of[5, 3, 8, 1, 9, 2, 5]shows. - Mutating while iterating. If you try to make this version in-place by removing elements from
xsinside a loop overxs, you will skip elements. In-place quicksort needs a different technique, which is the subject of the next chapters.
What This Version Costs
quicksort_simple is correct, but it does extra work. It scans each sublist three times, once per comprehension, and it allocates new lists at every level, so it needs O(n) extra memory per level of recursion. Concatenation with + also copies elements, so combining is not actually free in this implementation.
The next chapter looks at partitioning around a pivot in detail. That is the step that turns this sketch into an efficient algorithm.
Exercise
In quicksort_simple, explain why every recursive call receives a list strictly shorter than its input. What would break if the equal list were removed and the pivot were included in greater, using greater = [x for x in xs if x >= pivot]?
Show answer
The equal list always contains the pivot, so less and greater together have at most len(xs) - 1 elements, and each recursive call is strictly smaller. If the pivot goes into greater instead, greater can be the same length as the input. For example, [3, 3] picks pivot 3, gives less = [] and greater = [3, 3], and recurses on [3, 3] forever, ending in RecursionError. Any input whose pivot is its minimum value causes the same problem.
Exercise
Merge sort and quicksort are both divide-and-conquer sorts. For each one, say which step (divide or combine) does the linear-time work, and explain why quicksort's combine step can be trivial while merge sort's cannot.
Show answer
Merge sort divides by position in constant time and does linear work when it merges. Quicksort does linear work when it divides, comparing every element to the pivot, and its combine step is trivial. Because quicksort splits by value, every element on the left is less than every element on the right, so the sorted sides only need to be placed next to each other. Merge sort's halves have no ordering relationship, so they have to be interleaved by comparison.
Exercise
Without running code, trace quicksortsimple on [4, 3, 2, 1] (the pivot is xs[len(xs) // 2]). List the pivot chosen at each call and the depth of the deepest call. Then check your answer with quicksorttraced.
Show answer
[4, 3, 2, 1] picks pivot 2, giving less [1] and greater [4, 3]. [1] is a base case at depth 1. [4, 3] picks pivot 3 (index 1), giving less [] and greater [4], both base cases at depth 2. The deepest call is at depth 2 and the result is [1, 2, 3, 4]. The first split is fairly balanced, so the tree is shallow.