Sponsored
Sponsored
This approach involves breaking down the problem into smaller sub-problems, solving each sub-problem recursively, and combining the results to solve the larger problem. It's often used in sorting and searching algorithms, such as Merge Sort and Quick Sort.
Time Complexity: O(n log n) for the average and worst case.
Space Complexity: O(n) due to the temporary arrays used for merging.
1using System;
2
3class Program {
4 static void Merge(int[] arr, int l, int m, int r) {
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 int[] L = new int[n1];
8 int[] R = new int[n2];
9 for (int i = 0; i < n1; i++)
10 L[i] = arr[l + i];
11 for (int j = 0; j < n2; j++)
12 R[j] = arr[m + 1 + j];
13
14 int a = 0, b = 0;
15 int k = l;
16 while (a < n1 && b < n2) {
17 if (L[a] <= R[b]) {
18 arr[k] = L[a];
19 a++;
20 } else {
21 arr[k] = R[b];
22 b++;
23 }
24 k++;
25 }
26
27 while (a < n1) {
28 arr[k] = L[a];
29 a++;
30 k++;
31 }
32
33 while (b < n2) {
34 arr[k] = R[b];
35 b++;
36 k++;
37 }
38 }
39
40 static void MergeSort(int[] arr, int l, int r) {
41 if (l < r) {
42 int m = l + (r - l) / 2;
43 MergeSort(arr, l, m);
44 MergeSort(arr, m + 1, r);
45 Merge(arr, l, m, r);
46 }
47 }
48
49 static void Main() {
50 int[] arr = {12, 11, 13, 5, 6, 7};
51 MergeSort(arr, 0, arr.Length - 1);
52 Console.WriteLine(string.Join(", ", arr));
53 }
54}
This C# implementation sorts an array using the Merge Sort algorithm. It involves a recursive process of splitting and merging arrays.
This approach involves using two pointers or indices to traverse an array or linked list from two ends towards the center. It’s often applied to solve problems like palindrome checking, two-sum in a sorted array, and finding pairs in a sorted array.
Time Complexity: O(n) as each element is examined once in the worst case.
Space Complexity: O(1) because we're only using a fixed amount of additional space.
1
This JavaScript code utilizes two pointers to find two elements in a sorted array that sum to a target value. It iteratively positions pointers based on the comparison of current sums to the target.