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)
1public class MergeSort {
2
3 void merge(int arr[], int left, int mid, int right) {
4 int n1 = mid - left + 1;
5 int n2 = right - mid;
6 int L[] = new int[n1];
7 int R[] = new int[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;
15 int k = left;
16 while (i < n1 && j < n2) {
17 if (L[i] <= R[j]) {
18 arr[k] = L[i];
19 i++;
20 } else {
21 arr[k] = R[j];
22 j++;
23 }
24 k++;
25 }
26
27 while (i < n1) {
28 arr[k] = L[i];
29 i++;
30 k++;
31 }
32
33 while (j < n2) {
34 arr[k] = R[j];
35 j++;
36 k++;
37 }
38 }
39
40 void mergeSort(int arr[], int left, int right) {
41 if (left < right) {
42 int mid = left + (right - left) / 2;
43 mergeSort(arr, left, mid);
44 mergeSort(arr, mid + 1, right);
45 merge(arr, left, mid, right);
46 }
47 }
48
49 public static void main(String args[]) {
50 int arr[] = {12, 11, 13, 5, 6, 7};
51
52 MergeSort ob = new MergeSort();
53 ob.mergeSort(arr, 0, arr.length - 1);
54
55 System.out.println("Sorted array:");
56 for (int i = 0; i < arr.length; i++)
57 System.out.print(arr[i] + " ");
58 }
59}
This Java code implements the Merge Sort algorithm. It defines a merge
function to combine two sorted arrays into a single sorted array during the sorting process. The merge sort is recursively applied to each half of the 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.