Three steps
- Algorithms course
- Intermediate
- Lesson 65/80
- 4 min
Divide, conquer, combine.
Three steps
Divide and conquer has three steps: divide, conquer, combine.
The problem is split into subproblems, each solved recursively, then results are combined.
This approach is used in classic algorithms like merge sort, quick sort and binary search.
Example: merge sort
Merge sort follows these three steps: split the array in half, sort each half, merge the sorted halves.
This approach gives O(n log n) time; it scales well on large data.
Merge sort is a typical example of divide and conquer; the array splits in two at each level.
Practice Divide and sum
Write dc_sum(arr). Split the array in half, sum each recursively, then add. Print 10 with print(dc_sum([1, 2, 3, 4])).
Starter code
def dc_sum(arr):
# Divide and sumSample solution
def dc_sum(arr):
# Divide and sum
if len(arr) <= 1:
return sum(arr)
mid = len(arr) // 2
left = dc_sum(arr[:mid])
right = dc_sum(arr[mid:])
return left + right
print(dc_sum([1, 2, 3, 4]))Expected output
10
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the order of divide and conquer steps?
- Divide, conquer, combine Correct answer
- Divide, combine, conquer
- Conquer, divide, combine
- Combine, divide, conquer
Explanation: Divide, conquer, combine.
2 Subproblem
mid = len(arr) ____ 2
mid = len(arr) // 2
Explanation: // is right.
3 Three steps: match the terms
| Term | Meaning |
|---|---|
divide |
Split |
conquer |
Solve |
combine |
Merge |
recursion |
Self-call |