Module 6 · Recursion, Backtracking and Divide and Conquer · Lesson 22 of 40
Divide and conquer
Split a problem into halves, solve each half, and combine the answers. The idea behind merge sort and quick sort.
In this lesson · about 20 minutes
- Name the divide, conquer and combine steps
- Merge two sorted lists into one
- Explain why halving gives O(n log n) for merge sort
A teacher has 200 tests to sort by name. She gives half to each of two helpers. Each helper splits their pile again, and so on, until each pile has one test (already sorted!). Then the piles are merged back together, two at a time, keeping them in order. That is divide and conquer.
- Divide: split the problem into smaller parts (usually halves).
- Conquer: solve each part, usually with recursion. Tiny parts are the base case.
- Combine: join the parts' answers into the full answer.
Merging two sorted lists
The "combine" step of merge sort is the heart of it. Two sorted piles: look at the top of each, take the smaller, repeat. Each item is taken once, so merging is O(n).
Why O(n log n)?
Halving n items down to piles of 1 takes about log₂ n levels. At each level, all the merging together touches n items. So the total is n × log n.
Other divide and conquer examples
- Binary search: divide, but only one half needs conquering.
- Quick sort: pick a "pivot", put smaller items on its left and bigger on its right, then sort each side.
- Finding the max: the max of a list is the bigger of the max of each half.
How is this different from backtracking? Divide and conquer splits into separate parts and combines them. Backtracking tries choices and undoes them.
Try it: merge sort
Exercise
Merge two sorted lists
Write merge(a, b) that takes two sorted lists and returns one sorted list with all their items. Don't use sorted or .sort(): walk both lists with two indexes.
Exercise
Maximum by divide and conquer
Write dc_max(nums, low, high) that returns the biggest number between indexes low and high (both included) by splitting the range in half, finding each half's max, and returning the bigger one.
Check your understanding0 of 3 correct
Quiz score: 0 of 3
Exercises solved: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.