Module 6 · 15 min read · Free chapter
Divide and conquer
Divide and conquer splits a problem into smaller copies, solves them recursively and combines the answers. Its cost follows a recurrence such as T(n) = 2T(n/2) + n, which gives Θ(n log n). Strassen uses 7 products instead of 8, giving about Θ(n^2.81), and Karatsuba uses 3 instead of 4.
Start from zero: counting votes in a big constituency
Think of counting day in a constituency with 1,000 polling booths. No single officer counts every vote alone. The boxes are split among many tables, each table counts its own share, and the table totals are added to give the result.
That is divide and conquer. You break a big problem into smaller problems of the same kind, solve each smaller problem in the same way, and then combine the small answers into the big answer. The smaller problems can themselves be split again, until each piece is so small that the answer is obvious.
The trick only pays off if splitting and combining are cheap. Adding table totals is quick, so the method works well for counting. In this chapter we will see problems where a clever combine step turns a slow method into a fast one.
Why it matters. Merge sort, quicksort, binary search, fast multiplication and many graphics and geometry methods all follow this one pattern. GATE asks you to write their recurrences, solve them and compare them, so the pattern is worth learning once and well.
The pattern and its recurrence
Every divide-and-conquer algorithm has three steps. Divide the input into smaller subproblems, each of size about . Conquer each subproblem by a recursive call, and stop the recursion at a small base case. Combine the answers of the subproblems into the answer for the whole input.
If dividing and combining together cost , the running time obeys , with T of a small constant equal to a constant. This is exactly the form that the master theorem and the recursion tree solve, so the analysis of every algorithm in this chapter starts by reading off a, b and .
Binary search is the simplest case. It divides the sorted array at the middle, keeps only one half and throws the other away, and has nothing to combine. So , and , which gives .
Fast power uses the same shape. To compute the plain way you need 15 multiplications, but , , and , which is only 4 multiplications. For odd , , so in general the number of multiplications is .
power(x, n):
if n == 0: return 1
h = power(x, n / 2) // integer division
if n is even: return h * h
else: return x * h * h
Computers use this idea to raise numbers to huge powers in encryption. Some people call these one-subproblem cases "decrease and conquer", because nothing needs combining.
Why it matters. Once you can read a, b and from the code, the answer usually follows in one line. The rest of this chapter shows how changing a or , even by a little, changes the final running time.
Counting comparisons exactly: max-min and merge sort
GATE often asks not just for but for the exact number of comparisons. Two classic examples show how to get such counts from a recurrence with its base case.
Finding the maximum and the minimum together. The plain way scans once for the maximum, using comparisons, and once for the minimum, using another , so in total. Divide and conquer does better. Split the array into halves, find the max and min of each half, then compare the two maxima and the two minima, which costs 2 more comparisons.
This gives , with because one comparison of two elements decides both, and . Unrolling for gives , and . In general, for a power of 2, , against for the plain way.
The same count comes from a simple pairing view. Compare the elements in pairs, then find the maximum among the winners and the minimum among the losers. That costs , and for general the count is , which no comparison method can beat.
Merge sort. Its recurrence is , which gives . For the exact worst case, merging two lists of size needs at most comparisons, so with . For this is , and , which matches the formula .
Why it matters. Exact counts separate a well-prepared candidate from a guesser, because the options in such questions are often 10, 12, 14 and 16. Writing the base case correctly is half the work.
Quicksort analysed: worst, best, skewed and random pivots
Quicksort does its work in the divide step: partitioning elements around a pivot takes comparisons, and then the two parts are sorted separately. There is nothing to combine. So its running time depends entirely on how evenly the pivot splits the array.
Worst case. If the pivot is always the smallest or largest element, one part is empty and the other has elements. Then , which adds up to comparisons, that is . With the first or last element as pivot, this happens on sorted and reverse-sorted input.
Best case. If the pivot is always the median, , the same as merge sort, so .
A skewed but fixed split is still fine. Suppose every pivot splits the array 1 : 9. Then . In the recursion tree every full level costs at most , and the deepest path has length , which is still , so .
So quicksort is slow only when the splits are lopsided again and again. Even a split of 1 : 99 at every step gives ; only a split that leaves a constant number of elements on one side, again and again, gives .
Randomised quicksort chooses the pivot uniformly at random from the current part. Now no particular input is bad, because the luck lies in the coin tosses and not in the data.
Sort the elements by rank as . The elements and are compared only if one of them is the first pivot chosen from , ..., , which has probability .
Adding these probabilities over all pairs gives an expected number of comparisons of about , roughly 1.39 , for every input. So the expected time is . The worst case is still , but it needs extremely bad luck.
Why it matters. This is why library sorts use random or "median of three" pivots. The analysis also teaches a key idea: an algorithm can be made safe against any input by putting the randomness inside the algorithm.
Fewer multiplications: Karatsuba and Strassen
Sometimes divide and conquer wins not by splitting but by saving one recursive call. The two best-known examples are multiplying large numbers and multiplying matrices.
Karatsuba multiplication. The school method multiplies two -digit numbers in digit operations. Split each number into halves of digits: and . Then , which seems to need four half-size products.
The key observation is that . So the middle term is , and three products are enough. The recurrence becomes , and the master theorem gives , which is about .
Worked example. Multiply with , , and . The three products are , and . The middle term is , so the answer is .
Matrix multiplication. The direct method for matrices uses scalar multiplications. Splitting each matrix into four blocks gives eight block products, so , and splitting alone gains nothing.
Strassen's method forms seven special block products using sums and differences of blocks, and then rebuilds the four result blocks from them. It uses 7 block products and 18 block additions or subtractions. So , which is about .
In practice the extra additions make Strassen's method pay off only for fairly large matrices, and it can be less accurate with floating-point numbers. Karatsuba likewise beats the school method only beyond some hundreds of digits.
Why it matters. These two methods show that the exponent depends on a, the number of subproblems. Cutting a from 4 to 3 or from 8 to 7 changes the growth rate itself, which no faster processor can match for large inputs.
Smart combine steps: counting inversions and the closest pair
In some problems the brute-force method checks all pairs. Divide and conquer cuts this to when the combine step can deal with all the "cross" pairs, with one element in each half, in linear time.
Counting inversions. An inversion is a pair with . It measures how far an array is from sorted, which is how music and shopping sites compare two people's rankings. Checking every pair takes .
Instead, run merge sort and count while merging. Inversions inside the left half and inside the right half are counted by the recursive calls. When the merge takes an element from the right half, that element is smaller than every element still waiting in the left half, so we add the number of waiting left elements.
Worked example. Take 2, 4, 1, 3, 5, split as 2, 4 and 1, 3, 5, each half already sorted with 0 inversions. The merge takes 1 from the right while 2 and 4 wait, adding 2, then takes 2, then takes 3 while 4 waits, adding 1. The total is 3, which are the pairs (2, 1), (4, 1) and (4, 3), and the time is .
Closest pair of points. Given points in a plane, find the two that are nearest to each other. Sort the points by and split them by a vertical line through the median . Solve each half recursively and let be the smaller of the two best distances.
The only pairs left to check have one point on each side of the line, and both such points must lie within of the line. Keep only the points in this strip of width 2δ, sorted by . A packing argument shows that each strip point needs to be compared only with a constant number of the points that follow it, so the combine step is linear.
With the points sorted by and once at the start, . If the strip is sorted afresh at every level, the time becomes , which is still far better than the of checking every pair.
Why it matters. These two problems show the real art of divide and conquer, which is designing a combine step that handles all cross pairs without looking at them one by one. Air traffic systems use closest-pair ideas, and ranking comparison is a direct use of inversion counting.
Descriptive lens: how written papers ask this
Written papers for IT officer posts, state Assistant Programmer exams and university tests ask about divide and conquer in four ways:
- Explain the paradigm with its three steps and a worked example, usually merge sort or binary search.
- Derive the recurrence of a given algorithm and solve it by the recursion tree or the master theorem.
- Analyse quicksort in its best, worst and average cases and explain the role of the pivot.
- Show how a clever split reduces work, as in Karatsuba or Strassen, and compute the new exponent.
Practice questions (our own, not previous-year questions).
- Write a divide-and-conquer algorithm that finds both the maximum and the minimum of numbers, and prove that it uses comparisons when is a power of 2. (10 marks)
- Explain why randomised quicksort has an expected running time of for every input. (10 marks)
- Describe Karatsuba's method, apply it to and derive its running time. (15 marks)
Answer plan for question 3.
- Explain that the school method needs digit operations because every digit of one number meets every digit of the other.
- Split and , and write .
- Show that , so only three half-size products are needed.
- Apply it with , , and , giving , , and a middle term of 1714.
- Assemble and check it by direct multiplication.
- Write , apply case 1 of the master theorem with , and conclude that .
Quick revision
- Divide and conquer divides a problem, solves the parts recursively and combines the answers, giving .
- Binary search and fast power keep one half-size subproblem, so they take .
- Max-min by divide and conquer takes comparisons for a power of 2, against for the plain way.
- Merge sort takes comparisons in the worst case for a power of 2, which is 17 for .
- Quicksort is when the pivot is always an extreme element and for any fixed-proportion split.
- Randomised quicksort makes about 1.39 comparisons on average for every input.
- Karatsuba uses 3 half-size products and runs in about time.
- Strassen uses 7 block products and runs in about time, against for 8 products.
- Inversions are counted inside merge sort in .
- The closest pair of points is found in by checking a narrow strip around the dividing line.