Introduction
Last updated
Last updated
A divide and conquer algorithm is a strategy of solving a large problem by
breaking the problem into smaller sub-problems
solving the sub-problems, and
combining them to get the desired output.
Here are the steps involved:
Divide: Divide the given problem into sub-problems using recursion.
Conquer: Solve the smaller sub-problems recursively. If the subproblem is small enough, then solve it directly.
Combine: Combine the solutions of the sub-problems that are part of the recursive process to solve the actual problem.
Let us understand this concept with the help of an example.
Here, we will sort an array using the divide and conquer approach (ie. merge sort).
Let the given array be:Array for merge sort
Divide the array into two halves.Divide the array into two subparts Again, divide each subpart recursively into two halves until you get individual elements.Divide the array into smaller subparts
Now, combine the individual elements in a sorted manner. Here, conquer and combine steps go side by side.Combine the subparts
The complexity of the divide and conquer algorithm is calculated using the master theorem.
Let us take an example to find the time complexity of a recursive problem.
For a merge sort, the equation can be written as:
The divide and conquer approach divides a problem into smaller subproblems; these subproblems are further solved recursively. The result of each subproblem is not stored for future reference, whereas, in a dynamic approach, the result of each subproblem is stored for future reference.
Use the divide and conquer approach when the same subproblem is not solved multiple times. Use the dynamic approach when the result of a subproblem is to be used multiple times in the future.
Let us understand this with an example. Suppose we are trying to find the Fibonacci series. Then,
Divide and Conquer approach:
Dynamic approach: