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)
1using System;
2
3class MergeSort {
4 void Merge(int[] arr, int left, int mid, int right) {
5 int n1 = mid - left + 1;
6 int n2 = right - mid;
7 int[] L = new int[n1];
8 int[] R = new int[n2];
9
10 for (int i = 0; i < n1; ++i)
11 L[i] = arr[left + i];
12 for (int j = 0; j < n2; ++j)
13 R[j] = arr[mid + 1 + j];
14
15 int iIndex = 0, jIndex = 0;
16 int k = left;
17 while (iIndex < n1 && jIndex < n2) {
18 if (L[iIndex] <= R[jIndex]) {
19 arr[k] = L[iIndex];
20 iIndex++;
21 } else {
22 arr[k] = R[jIndex];
23 jIndex++;
24 }
25 k++;
26 }
27
28 while (iIndex < n1) {
29 arr[k] = L[iIndex];
30 iIndex++;
31 k++;
32 }
33
34 while (jIndex < n2) {
35 arr[k] = R[jIndex];
36 jIndex++;
37 k++;
38 }
39 }
40
41 void MergeSortFunction(int[] arr, int left, int right) {
42 if (left < right) {
43 int mid = left + (right - left) / 2;
44
45 MergeSortFunction(arr, left, mid);
46 MergeSortFunction(arr, mid + 1, right);
47
48 Merge(arr, left, mid, right);
49 }
50 }
51
52 public static void Main(String[] args) {
53 int[] arr = {12, 11, 13, 5, 6, 7};
54 MergeSort ob = new MergeSort();
55 ob.MergeSortFunction(arr, 0, arr.Length - 1);
56 Console.WriteLine("Sorted array:");
57 Console.WriteLine(string.Join(" ", arr));
58 }
59}
This C# code is an implementation of the Merge Sort algorithm. It contains a Merge
function that merges two halves of an array and a MergeSortFunction
that sorts these halves recursively.
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)
1#include <iostream>
2#include <vector>
using namespace std;
int fib(int n, vector<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);
}
int main() {
int n = 10;
vector<int> dp(n + 1, -1);
cout << "Fibonacci number is " << fib(n, dp) << endl;
return 0;
}
This C++ code implements a Fibonacci sequence calculator using Dynamic Programming. Memoization is employed to store results of previous computations in a vector, eliminating redundant calculations and reducing execution time.