The Divide and Conquer strategy is an algorithm design paradigm used to solve problems efficiently. The idea is to break down a problem into smaller subproblems, solve each subproblem recursively, and then combine their results to solve the original problem.
The general structure for divide and conquer algorithms:
This paradigm is commonly used in algorithms like Binary Search, Merge Sort, and Quick Sort.
The Binary Search Algorithm is a classic example of the divide and conquer strategy. It is used to find an element in a sorted array efficiently.
class BinarySearch {
// Function to perform binary search
public int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if target is present at mid
if (arr[mid] == target) return mid;
// If target is smaller than mid, it can only be in the left half
if (arr[mid] > target) right = mid - 1;
else left = mid + 1;
}
return -1; // Element not found
}
public static void main(String[] args) {
BinarySearch bs = new BinarySearch();
int[] arr = {2, 3, 4, 10, 40};
int result = bs.binarySearch(arr, 10);
if (result != -1)
System.out.println("Element found at index " + result);
else
System.out.println("Element not found");
}
}