Sponsored
Sponsored
This approach breaks down the problem into smaller subproblems. We solve the subproblems recursively and then combine their solutions to solve the original problem. This is useful in problems like merge sort or quicksort.
Time Complexity: O(n log n)
Space Complexity: O(n)
1def mergeSort(arr):
2 if len(arr) > 1:
3 mid = len(arr) // 2
4 L = arr[:mid]
5 R = arr[mid:]
6 mergeSort(L)
7 mergeSort(R)
8 i = j = k = 0
9 while i < len(L) and j < len(R):
10 if L[i] < R[j]:
11 arr[k] = L[i]
12 i += 1
13 else:
14 arr[k] = R[j]
15 j += 1
16 k += 1
17 while i < len(L):
18 arr[k] = L[i]
19 i += 1
20 k += 1
21 while j < len(R):
22 arr[k] = R[j]
23 j += 1
24 k += 1
25
26arr = [12, 11, 13, 5, 6, 7]
27mergeSort(arr)
28print(arr)
29
This Python code for merge sort divides the list into halves recursively, sorts each half, and then merges them back together in a sorted manner.
This approach uses a binary heap data structure to sort the elements. Unlike the recursive nature of merge sort, heap sort uses an iterative process to build a max heap and then extracts the maximum element one by one.
Time Complexity: O(n log n)
Space Complexity: O(1)
1function
This JavaScript implementation leverages the heap sort technique, building a heap and using it to sort the array iteratively.