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)
1#include <iostream>
2using namespace std;
3
4void merge(int arr[], int l, int m, int r) {
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 int L[n1], R[n2];
8 for (int i = 0; i < n1; i++)
9 L[i] = arr[l + i];
10 for (int j = 0; j < n2; j++)
11 R[j] = arr[m + 1 + j];
12 int i = 0, j = 0, k = l;
13 while (i < n1 && j < n2) {
14 arr[k++] = L[i] <= R[j] ? L[i++] : R[j++];
15 }
16 while (i < n1)
17 arr[k++] = L[i++];
18 while (j < n2)
19 arr[k++] = R[j++];
20}
21
22void mergeSort(int arr[], int l, int r) {
23 if (l < r) {
24 int m = l + (r - l) / 2;
25 mergeSort(arr, l, m);
26 mergeSort(arr, m + 1, r);
27 merge(arr, l, m, r);
28 }
29}
30
31int main() {
32 int arr[] = {12, 11, 13, 5, 6, 7};
33 int arr_size = sizeof(arr) / sizeof(arr[0]);
34 mergeSort(arr, 0, arr_size - 1);
35 for (int i = 0; i < arr_size; i++)
36 cout << arr[i] << " ";
37 return 0;
38}
39
This C++ code is a similar implementation of the merge sort algorithm. It recursively sorts and merges the array using the same divide and conquer strategy.
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)
1def
This Python function for heap sort constructs a heap and sorts the array by continuously removing the largest element.