Recursive structure
- Algorithms course
- Intermediate
- Lesson 66/80
- 4 min
Divide and conquer is recursive.
Recursive structure
Divide and conquer is built on recursion. Each subproblem is solved by the same function.
The base case stops when the subproblem is small enough to solve directly; this is essential.
Recursion shrinks the problem at each level; complex structures become simple.
Base case
The base case is usually a single-element or empty array. Here the work is done directly, no split.
Without a base case recursion loops forever; the stack overflows and the program crashes.
The base case is the cornerstone of recursive solutions; it must be defined correctly.
Practice Divide and max
Write dc_max(arr). Split in half, find the max of each recursively, return the larger. Print 5 with print(dc_max([3, 1, 4, 1, 5])).
Starter code
def dc_max(arr):
# Divide and find maxSample solution
def dc_max(arr):
# Divide and find max
if len(arr) == 1:
return arr[0]
mid = len(arr) // 2
left = dc_max(arr[:mid])
right = dc_max(arr[mid:])
return left if left > right else right
print(dc_max([3, 1, 4, 1, 5]))Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Base condition
if len(arr) <= ____:
if len(arr) <= 1:
Explanation: 1 is right.
2 Recursive structure: match the terms
| Term | Meaning |
|---|---|
base case |
Stops |
recursion |
Splits |
subproblem |
Subproblem |
combine |
Merges |
3 What is the base case's role in divide and conquer?
- Reduce memory
- Speed up
- Stop recursion Correct answer
- Sort
Explanation: Stop recursion.