Divide and conquer (1) divides the input into smaller independent subproblems, (2) conquers each recursively, and (3) combines the answers. Merge sort, quick sort, and binary search are classic examples. The running time is described by a recurrence such as T(n) = 2T(n/2) + O(n), which gives O(n log n) for merge sort.
Remember
solve(range):
if range is small: return answer directly
left = solve(first half)
right = solve(second half)
return combine(left, right)
Reference
Cheat Sheet
Keep these facts handy while you work with Divide and Conquer in C in C.
Topic
Detail
Divide
Split the input
Conquer
Solve recursively
Combine
Merge answers
Examples
Merge sort, quick sort, binary search
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Greedy Algorithms in C.
Example 1 — Maximum of an array by halves
Six values require 11 calls (2n - 1).
C
#include <stdio.h>
static int calls;
static int max_range(const int a[], int lo, int hi) {
calls++;
if (lo == hi) return a[lo];
int mid = lo + (hi - lo) / 2;
int left = max_range(a, lo, mid);
int right = max_range(a, mid + 1, hi);
return left > right ? left : right;
}
int main(void) {
int a[] = {3, 9, 2, 7, 5, 8};
int m = max_range(a, 0, 5);
printf("max = %d (%d calls)\n", m, calls);
return 0;
}
Output
max = 9 (11 calls)
How It Works
The array is split into halves until single elements remain (six leaves).
Each internal call combines two answers with a comparison.
A binary tree with six leaves has 11 nodes, hence 11 calls. A simple loop would be just as fast; the example shows the pattern.
Edge Cases & Pitfalls
Check these before relying on Divide and Conquer in C in real programs.
overlap
Overlapping subproblems
If halves share work (as in Fibonacci), divide and conquer repeats it. Use DP instead.
small
No cutoff for small inputs
Switching to insertion sort for tiny ranges speeds up real implementations.
Remember
Key Takeaways
Divide, conquer, combine.
Independent subproblems.
Recurrences give the cost.
One line: Divide and conquer (1) divides the input into smaller independent subproblems, (2) conquers each recursively, and (3) combines the answers.
Frequently Asked Questions
A strategy that splits a problem into independent subproblems, solves them recursively, and combines their solutions.
Merge sort, quick sort, binary search, and fast exponentiation, among others.
Continue with "Greedy Algorithms in C" next. Coin change and activity selection with greedy choices. The C Algorithm Techniques hub lists every topic in order.