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.
1#include <iostream>
2#include <vector>
3
4void merge(std::vector<int>& arr, int l, int m, int r) {
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 std::vector<int> L(n1);
8 std::vector<int> R(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 int i = 0, j = 0, k = l;
14 while (i < n1 && j < n2) {
15 if (L[i] <= R[j]) {
16 arr[k] = L[i];
17 i++;
18 } else {
19 arr[k] = R[j];
20 j++;
21 }
22 k++;
23 }
24 while (i < n1) {
25 arr[k] = L[i];
26 i++;
27 k++;
28 }
29 while (j < n2) {
30 arr[k] = R[j];
31 j++;
32 k++;
33 }
34}
35
36void mergeSort(std::vector<int>& arr, int l, int r) {
37 if (l < r) {
38 int m = l+(r-l)/2;
39 mergeSort(arr, l, m);
40 mergeSort(arr, m+1, r);
41 merge(arr, l, m, r);
42 }
43}
44
45void printArray(const std::vector<int>& arr) {
46 for (int x : arr)
47 std::cout << x << " ";
48 std::cout << std::endl;
49}
50
51int main() {
52 std::vector<int> arr = {12, 11, 13, 5, 6, 7};
53 std::cout << "Given array is \n";
54 printArray(arr);
55
56 mergeSort(arr, 0, arr.size() - 1);
57
58 std::cout << "Sorted array is \n";
59 printArray(arr);
60 return 0;
61}
This C++ solution uses the Merge Sort algorithm, similar to the C solution. It utilizes a vector instead of arrays for better dynamic size handling.
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 C code demonstrates using a two-pointer technique in a sorted array to find two numbers that sum up to a target. It initializes pointers at each end of the array and adjusts them till the required sum is found or pointers cross.