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.
1def mergeSort(arr):
2 if len(arr) > 1:
3 mid = len(arr)//2
4 L = arr[:mid]
5 R = arr[mid:]
6
7 mergeSort(L)
8 mergeSort(R)
9
10 i = j = k = 0
11
12 while i < len(L) and j < len(R):
13 if L[i] < R[j]:
14 arr[k] = L[i]
15 i += 1
16 else:
17 arr[k] = R[j]
18 j += 1
19 k += 1
20
21 while i < len(L):
22 arr[k] = L[i]
23 i += 1
24 k += 1
25
26 while j < len(R):
27 arr[k] = R[j]
28 j += 1
29 k += 1
30
31arr = [12, 11, 13, 5, 6, 7]
32mergeSort(arr)
33print("Sorted array is", arr)
This Python implementation of Merge Sort uses recursion to sort the array. The array is divided into halves, recursively sorted, and merged.
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.