Sub topic 1
The Divide-and-Conquer Idea
Merge sort is the standard example of a strategy called divide and conquer. Before you write a merge function or analyze a recurrence, you need a clear picture of that strategy: what the three steps are, where the real work happens, and what makes a problem a good or bad fit. This chapter builds that picture. Later chapters cover the merge step, the recursion, and the analysis in detail.
Prerequisites
This chapter assumes you already know:
- Basic Python: functions, loops, and list slicing such as
items[:mid]. - Arrays/lists and zero-based indexing.
- Recursion and the call stack: a function can call itself, and each call has its own local variables.
- Big-O notation at the level of "O(n) means work grows in proportion to n."
You do not need to know any sorting algorithm yet.
The Three Steps
Divide and conquer is a recursive problem-solving pattern made of three steps:
- Divide: split the problem into smaller subproblems of the same kind.
- Conquer: solve each subproblem recursively. When a subproblem is small enough, solve it directly. This direct case is the base case.
- Combine: merge the subproblem solutions into a solution for the original problem.
The pattern works because of one property: a solution to a big instance can be built from solutions to smaller instances of the same problem. Sorting has this property. If you have the left half of a list in sorted order and the right half in sorted order, you can build the whole sorted list from them. Merge sort applies the three steps like this:
| Step | What merge sort does | Cost per call |
|---|---|---|
| Divide | Find the midpoint and split the list into two halves | O(1) with indices, O(n) if you copy slices |
| Conquer | Sort each half recursively; a list of 0 or 1 elements is already sorted | Two recursive calls |
| Combine | Merge the two sorted halves into one sorted list | O(n) |
Merge sort's divide step is trivial and its combine step does all the work. That is the main fact to carry into the rest of the tutorial.
Seeing the Shape of the Recursion
The diagram below shows the full divide-and-combine structure for a seven-element list. The top half splits the list until every piece has one element. The bottom half merges the pieces back together.
Notice that the split is not always perfectly even. With seven elements, one half gets three and the other gets four. Divide and conquer does not need exact halves. It needs each subproblem to be a constant fraction smaller than its parent, so the recursion reaches the base case after about log₂ n levels.
You can print the divide phase yourself. This function only splits. It does not sort or combine anything:
def show_splits(items, depth=0):
print(" " * depth + str(items))
if len(items) <= 1:
return
mid = len(items) // 2
show_splits(items[:mid], depth + 1)
show_splits(items[mid:], depth + 1)
show_splits([38, 27, 43, 3, 9, 82, 10])Output:
[38, 27, 43, 3, 9, 82, 10]
[38, 27, 43]
[38]
[27, 43]
[27]
[43]
[3, 9, 82, 10]
[3, 9]
[3]
[9]
[82, 10]
[82]
[10]The indentation is the recursion depth. The deepest line is at depth 3, and ⌈log₂ 7⌉ = 3. The calls also run in depth-first order: the whole left subtree finishes before the right subtree starts. That order matters later when we look at how much memory is live at any moment.
A Smaller Example: Maximum of a List
To separate the pattern from sorting, here it is applied to finding a maximum. This version works on index ranges, which avoids the cost of copying slices:
def dc_max(items, lo, hi):
"""Return the largest value in items[lo:hi]. Requires hi > lo."""
if hi - lo == 1: # base case: one element
return items[lo]
mid = (lo + hi) // 2 # divide
left_best = dc_max(items, lo, mid) # conquer left
right_best = dc_max(items, mid, hi) # conquer right
return left_best if left_best >= right_best else right_best # combine
data = [38, 27, 43, 3, 9, 82, 10]
print(dc_max(data, 0, len(data))) # 82All three steps are present, and the combine is a single comparison. This algorithm is correct, but it is no faster than a simple loop. Both make n − 1 comparisons. Divide and conquer is a way to organize a solution, and it does not automatically make that solution faster. It pays off when the combine step can use structure in the sub-solutions that the original problem did not have. For sorting, that structure is "each half is already sorted," and the merge uses it to finish in linear time.
Where the Work Lives
Different divide-and-conquer algorithms put their effort in different steps. Comparing them shows what is special about merge sort.
| Algorithm | Divide | Subproblems | Combine | Total time |
|---|---|---|---|---|
| Binary search | O(1): pick the middle | 1 of size n/2 | O(1): nothing | O(log n) |
| Max by halves | O(1): pick the middle | 2 of size n/2 | O(1): one comparison | O(n) |
| Merge sort | O(1): pick the middle | 2 of size n/2 | O(n): merge | O(n log n) |
| Quicksort | O(n): partition around a pivot | 2 of variable size | O(1): nothing | O(n log n) average, O(n²) worst |
Merge sort and quicksort mirror each other. Quicksort does its hard work before recursing: partitioning puts every small element left of every large one, so nothing remains to combine. Merge sort splits without looking at the values and does its hard work after recursing. That difference has consequences:
- Merge sort's split is always balanced, because it ignores the data. Its running time does not depend on the input order. A later chapter derives this from the recurrence T(n) = 2T(n/2) + O(n).
- Quicksort's split depends on the pivot. A bad pivot gives unbalanced subproblems and quadratic time.
- Merging two arrays is hard to do in place, so array merge sort usually needs extra memory. Partitioning is easy to do in place.
When Divide and Conquer Fits
The pattern works well when these conditions hold:
- Same problem, smaller size. Each subproblem is a smaller instance of the original problem, so one function can solve all of them.
- Independent subproblems. Solving the left half does not require knowing anything about the right half. This also makes the halves easy to run in parallel.
- Cheap combine. Combining costs no more than about linear time in the size of the subproblem. A quadratic combine would cancel the benefit of splitting.
- Balanced splits. Each subproblem is a constant fraction of the parent's size, which keeps the depth logarithmic.
Common Mistakes
These errors come up often when people first write divide-and-conquer code:
- A missing or wrong base case. If the base case is
len(items) == 1and the function is ever called on an empty list, the recursion never stops. Merge sort useslen(items) <= 1to cover both cases. - A split that does not shrink. Splitting a range
[lo, hi)as[lo, mid]and[mid, hi)with an inclusive bound, or computingmidso that one side is empty and the other is the whole range, causes infinite recursion on two-element inputs. With half-open ranges andmid = (lo + hi) // 2, both sides are non-empty wheneverhi - lo >= 2. - Overlapping subproblems. If the subproblems share work, as in computing Fibonacci numbers with
fib(n-1) + fib(n-2), plain divide and conquer recomputes the same answers exponentially many times. That situation calls for dynamic programming. Merge sort's halves never overlap. - Assuming the pattern makes things faster. As
dc_maxshowed, splitting only helps when the combine step uses the sub-solutions' structure.
Exercises
Exercise
Write a divide-and-conquer function dc_sum(items, lo, hi) that returns the sum of items[lo:hi], and return 0 for an empty range. Identify the divide, conquer, and combine steps.
Show answer
def dcsum(items, lo, hi): if hi - lo == 0: return 0 if hi - lo == 1: return items[lo] mid = (lo + hi) // 2 return dcsum(items, lo, mid) + dc_sum(items, mid, hi) Divide: compute mid. Conquer: the two recursive calls. Combine: add the two results, which costs O(1). Total time is O(n), the same as a loop.
Exercise
A student writes the split as mid = (lo + hi) // 2, then recurses on [lo, mid + 1) and [mid + 1, hi). What happens when hi - lo == 2?
Show answer
With lo = 0 and hi = 2, mid = 1, so the calls are on [0, 2) and [2, 2). The first call is the same range as the parent, so the recursion never reaches the base case and eventually raises RecursionError. The correct split is [lo, mid) and [mid, hi).
Exercise
For n = 16, how many levels does merge sort's recursion tree have below the root, and how many single-element subproblems sit at the bottom level?
Show answer
log2(16) = 4 levels below the root, and 16 single-element leaves, one for each input element.
Exercise
Merge sort and quicksort are both divide-and-conquer sorts. In one sentence each, say where each one does its main work and why merge sort's running time does not depend on the input order.
Show answer
Quicksort does its work in the divide step by partitioning around a pivot, while merge sort does its work in the combine step by merging. Merge sort splits at the midpoint without looking at the values, so its subproblem sizes, and therefore its running time, are the same for every input of size n.