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)
1def merge(arr, left, mid, right):
2 n1 = mid - left + 1
3 n2 = right - mid
4 L = arr[left:left + n1]
5 R = arr[mid + 1:mid + 1 + n2]
6
7 i = 0
8 j = 0
9 k = left
10 while i < n1 and j < n2:
11 if L[i] <= R[j]:
12 arr[k] = L[i]
13 i += 1
14 else:
15 arr[k] = R[j]
16 j += 1
17 k += 1
18
19 while i < n1:
20 arr[k] = L[i]
21 i += 1
22 k += 1
23
24 while j < n2:
25 arr[k] = R[j]
26 j += 1
27 k += 1
28
29def mergeSort(arr, left, right):
30 if left < right:
31 mid = (left + right) // 2
32 mergeSort(arr, left, mid)
33 mergeSort(arr, mid + 1, right)
34 merge(arr, left, mid, right)
35
36arr = [12, 11, 13, 5, 6, 7]
37mergeSort(arr, 0, len(arr) - 1)
38print("Sorted array:")
39print(arr)
This Python code applies the Merge Sort algorithm using recursion. It consists of a merge
function that combines two sorted halves into a sorted array and a mergeSort
function that recursively sorts the array halves.
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.