This algorithmic paradigm involves breaking a large problem into smaller sub-problems, solving them, and combining the results.
The Three Stages:
- Divide: Break the problem into sub-problems of the same type.
- Conquer: Solve the sub-problems recursively. If they are small enough, solve them directly.
- Combine: Merge the solutions of the sub-problems to get the final solution.
Java Implementation: Finding the Sum using Divide and Conquer
public class DivideConquerExample {
public static int sum(int[] arr, int start, int end) {
// Base Case: Only one element
if (start == end) {
return arr[start];
}
// Divide
int mid = (start + end) / 2;
// Conquer (Recursive calls)
int leftSum = sum(arr, start, mid);
int rightSum = sum(arr, mid + 1, end);
// Combine
return leftSum + rightSum;
}
public static void main(String[] args) {
int[] data = {1, 2, 3, 4, 5, 6};
System.out.println("Total Sum: " + sum(data, 0, data.length - 1));
}
}