A stack of exam papers has to be sorted by name, and you're not on your own. You split the stack in two: one half for you, one for your friend. Each of you sorts your half, then the two sorted stacks are put together. Putting two sorted stacks together is far easier than sorting the whole stack at once.
This way of working is called divide and conquer. A big problem is split into smaller problems of the same kind, for example sorting smaller stacks. Merge sort, quick sort and binary search all use this pattern.
Three steps: divide, conquer, combine
- Divide: split the problem into smaller parts, usually into two.
- Conquer: solve each part. When a part is small enough, you know its answer right away.
- Combine: join the parts' answers into the answer to the big problem.
In the exam paper example: splitting the stack is divide, you and your friend sorting your own halves is conquer, and putting the two stacks together is combine.
Another example is sorting 8 numbers with merge sort (the sort in the next lesson):
| Step | Result |
|---|---|
| Divide | [38, 27, 43, 3] [9, 82, 10, 55] |
| Divide | [38, 27] [43, 3] [9, 82] [10, 55] |
| Divide, then conquer | 8 parts of 1 number each, and 1 number is always sorted |
| Combine | [27, 38] [3, 43] [9, 82] [10, 55] |
| Combine | [3, 27, 38, 43] [9, 10, 55, 82] |
| Combine | [3, 9, 10, 27, 38, 43, 55, 82] |
In code, divide and conquer is written with recursion: a function that calls itself on a smaller version of the same problem. In the code below, mergeSort for 8 numbers calls mergeSort for 4 numbers. That call calls mergeSort for 2 numbers, then for 1 number. At 1 number the calls stop, because there's a base case: a condition where the function returns its answer right away, without calling itself again. The base case is arr.length <= 1.
Here is the full merge sort in JavaScript:
function mergeSort(arr) {
if (arr.length <= 1) return arr; // base case: 1 number is already sorted
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid)); // divide: left half
const right = mergeSort(arr.slice(mid)); // divide: right half
return merge(left, right); // combine
}
function merge(left, right) {
const out = [];
let i = 0;
let j = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) out.push(left[i++]);
else out.push(right[j++]);
}
return out.concat(left.slice(i), right.slice(j));
}
console.log(mergeSort([38, 27, 43, 3, 9, 82, 10, 55]));
// [3, 9, 10, 27, 38, 43, 55, 82]
- The base case goes at the very top, so the recursion is sure to stop.
midis the middle index.arr.slice(0, mid)takes the left half, andarr.slice(mid)takes the right half. Both halves are sorted by callingmergeSortagain.merge(left, right)is the combine step: it joins two sorted arrays by comparing the front number of each array. The details are in the next lesson, Merge Sort.
Why there are so few levels
One level is one round of splitting every part in two, like one Divide row in the table above. 8 numbers need 3 levels: a part of 8 numbers becomes 4, then 2, then 1. With 16 numbers, how many levels? Only 4: twice the data, just one more level. This number of levels is called log n: how many times n (the amount of data) can be halved until 1 is left. 1,000 numbers need only about 10 levels.
In merge sort, the combine step on each level handles all n numbers once. There are log n levels, so the total is about n × log n steps, written in Big-O as O(n log n): about 10,000 steps for 1,000 numbers. Bubble sort needs about 500,000 comparisons for the same data.
Another example: the largest number
Finding the largest number in [3, 7, 1, 9, 4] can be split too. The largest number in the left half [3, 7, 1] is 7, and in the right half [9, 4] it is 9. The combine step just takes the bigger of those two answers: 9.
Binary search is divide and conquer as well. The difference is that binary search works on only one half, and the other half is thrown away. Quick sort separates its data into the numbers smaller and the numbers bigger than one reference number, called the pivot. Then it sorts both parts.
💡 When isn't it divide and conquer? The pattern fits best when the parts don't depend on each other: the left half can be sorted without waiting for the right half. When the same part is calculated again and again, it's cheaper to store its result, so it is calculated only once. That method is called dynamic programming, and it is covered in another lesson.
⚠️ Recursion that never stops, or results never combined
- A missing or wrong base case. Without
if (arr.length <= 1) return arr;, the function keeps calling itself. In the end JavaScript stops with the errorMaximum call stack size exceeded, which means the list of function calls that haven't finished has passed its limit. - The problem doesn't shrink. Every call has to get a smaller part. If
mergeSort(arr)callsmergeSort(arr)with the same array, it never reaches the base case. - Forgetting to combine. Sorting the two halves isn't enough. Without
merge, you only get two pieces that are each sorted, not one sorted array.
TL;DR: Divide and conquer is a pattern with three steps: divide (split the problem into smaller parts), conquer (solve each part, usually with recursion) and combine (join the results). Recursion is a function calling itself on a smaller problem. The base case is a condition where the function returns its answer right away, without calling itself again, so the recursion stops there. When data is halved again and again, the number of levels (how many times every part is split in two) is only log n: twice the data, one more level. Merge sort uses this pattern, and its combine step on each level handles n numbers, so merge sort is O(n log n).
⚡ Divide, conquer, combine
Meaning: The divide and conquer pattern has three steps. Divide: split the problem into smaller parts, usually two. Conquer: solve each part. Combine: join the parts' answers into the answer to the big problem. For example, you and a friend split a stack of exam papers in two, each of you sorts one half, then you put the halves together.
⚡ Recursion and the base case
Write:
function mergeSort(arr) {
if (arr.length <= 1) return arr; // base case: 1 number is already sorted
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid)); // divide: left half
const right = mergeSort(arr.slice(mid)); // divide: right half
return merge(left, right); // combine
}
Meaning: mergeSort splits the array at the middle index (mid), sorts each half by calling itself, then joins the two halves with merge (combine). A function that calls itself on a smaller problem is called recursion. The base case at the top (arr.length <= 1) returns the array right away, without calling the function again, so the recursion is sure to stop. Without it, the function keeps calling itself until you get the error Maximum call stack size exceeded.
⚡ Very few levels
Guess first: splitting 8 numbers until each part holds 1 number takes 3 levels, that is, 3 rounds of splitting (8, 4, 2, 1). How many levels for 16 numbers?
Only 4. Twice the data, just one more level. This number of levels is called log n, where n is the amount of data.
Meaning: In merge sort, the combine step on each level handles all n numbers once, and there are log n levels. So the total is O(n log n).