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 <iostream>
2using namespace std;
3
4void merge(int arr[], int left, int mid, int right) {
5 int n1 = mid - left + 1;
6 int n2 = right - mid;
7 int L[n1], R[n2];
8
9 for (int i = 0; i < n1; i++)
10 L[i] = arr[left + i];
11 for (int j = 0; j < n2; j++)
12 R[j] = arr[mid + 1 + j];
13
14 int i = 0, j = 0, k = left;
15 while (i < n1 && j < n2) {
16 if (L[i] <= R[j]) {
17 arr[k] = L[i];
18 i++;
19 } else {
20 arr[k] = R[j];
21 j++;
22 }
23 k++;
24 }
25
26 while (i < n1) {
27 arr[k] = L[i];
28 i++;
29 k++;
30 }
31
32 while (j < n2) {
33 arr[k] = R[j];
34 j++;
35 k++;
36 }
37}
38
39void mergeSort(int arr[], int left, int right) {
40 if (left < right) {
41 int mid = left + (right - left) / 2;
42
43 mergeSort(arr, left, mid);
44 mergeSort(arr, mid + 1, right);
45
46 merge(arr, left, mid, right);
47 }
48}
49
50int main() {
51 int arr[] = {12, 11, 13, 5, 6, 7};
52 int arr_size = sizeof(arr) / sizeof(arr[0]);
53
54 mergeSort(arr, 0, arr_size - 1);
55
56 cout << "Sorted array: \n";
57 for (int i = 0; i < arr_size; i++)
58 cout << arr[i] << " ";
59 return 0;
60}
This C++ code implements the Merge Sort algorithm using the Divide and Conquer strategy, similar to the C implementation. The merge
function is used to combine two sorted subarrays into a main 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)
1using System;
2
class Fibonacci {
int Fib(int n, int[] dp) {
if (n <= 1) return n;
if (dp[n] != -1) return dp[n];
return dp[n] = Fib(n-1, dp) + Fib(n-2, dp);
}
public static void Main(string[] args) {
int n = 10;
int[] dp = new int[n + 1];
Array.Fill(dp, -1);
Fibonacci fibonacci = new Fibonacci();
Console.WriteLine("Fibonacci number is " + fibonacci.Fib(n, dp));
}
}
This C# code is a dynamic programming solution for computing Fibonacci numbers. It uses a memoization technique with an integer array to optimize the recursive calls, ensuring that each subproblem is solved only once.