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)
1function mergeSort(arr) {
2 if (arr.length > 1) {
3 const mid = Math.floor(arr.length / 2);
4 const L = arr.slice(0, mid);
5 const R = arr.slice(mid);
6
7 mergeSort(L);
8 mergeSort(R);
9
10 let i = 0, j = 0, k = 0;
11 while (i < L.length && j < R.length) {
12 if (L[i] < R[j]) {
13 arr[k++] = L[i++];
14 } else {
15 arr[k++] = R[j++];
16 }
17 }
18
19 while (i < L.length) arr[k++] = L[i++];
20 while (j < R.length) arr[k++] = R[j++];
21 }
22 return arr;
23}
24
25const arr = [12, 11, 13, 5, 6, 7];
26console.log(mergeSort(arr));
27
This JavaScript code handles merge sort by recursively dividing the array into halves and merging them in a sorted order.
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)
1#
This C code sorts an array using heap sort, an iterative algorithm utilizing a binary heap to extract the largest elements and build the sorted array.