Sponsored
Sponsored
This approach involves breaking down the problem into smaller subproblems, solving each subproblem recursively, and then combining the results. This is a classic Divide and Conquer approach which can be applied to a variety of problems, such as sorting algorithms (e.g., Merge Sort).
Time Complexity: O(n log n)
Space Complexity: O(n)
1#include <stdio.h>
2
3void merge(int arr[], int left, int mid, int right) {
4 int i, j, k;
5 int n1 = mid - left + 1;
6 int n2 = right - mid;
7 int L[n1], R[n2];
8
9 for (i = 0; i < n1; i++)
10 L[i] = arr[left + i];
11 for (j = 0; j < n2; j++)
12 R[j] = arr[mid + 1 + j];
13
14 i = 0;
15 j = 0;
16 k = left;
17 while (i < n1 && j < n2) {
18 if (L[i] <= R[j]) {
19 arr[k] = L[i];
20 i++;
21 } else {
22 arr[k] = R[j];
23 j++;
24 }
25 k++;
26 }
27
28 while (i < n1) {
29 arr[k] = L[i];
30 i++;
31 k++;
32 }
33
34 while (j < n2) {
35 arr[k] = R[j];
36 j++;
37 k++;
38 }
39}
40
41void mergeSort(int arr[], int left, int right) {
42 if (left < right) {
43 int mid = left + (right - left) / 2;
44
45 mergeSort(arr, left, mid);
46 mergeSort(arr, mid + 1, right);
47
48 merge(arr, left, mid, right);
49 }
50}
51
52int main() {
53 int arr[] = {12, 11, 13, 5, 6, 7};
54 int arr_size = sizeof(arr) / sizeof(arr[0]);
55
56 mergeSort(arr, 0, arr_size - 1);
57
58 printf("Sorted array: \n");
59 for (int i = 0; i < arr_size; i++)
60 printf("%d ", arr[i]);
61 return 0;
62}
This C code implements the Merge Sort algorithm using the Divide and Conquer strategy. The array is divided into two halves, each is sorted recursively, and then the two halves are merged together. The merge
function combines two sorted subarrays into a single sorted array.
Dynamic Programming (DP) is an approach that solves complex problems by breaking them down into simpler subproblems and storing the results to avoid recomputing. It's particularly useful for optimization problems where decisions depend on previous decisions.
Time Complexity: O(n)
Space Complexity: O(n)
1import
This Java code provides a dynamic programming implementation to find Fibonacci numbers. The fib
method uses an integer array to store intermediate results to ensure the function runs in linear time.