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)
1public class MergeSort {
2 public static void merge(int arr[], int l, int m, int r) {
3 int n1 = m - l + 1;
4 int n2 = r - m;
5 int L[] = new int[n1];
6 int R[] = new int[n2];
7 for (int i = 0; i < n1; ++i)
8 L[i] = arr[l + i];
9 for (int j = 0; j < n2; ++j)
10 R[j] = arr[m + 1 + j];
11 int i = 0, j = 0;
12 int k = l;
13 while (i < n1 && j < n2) {
14 if (L[i] <= R[j]) {
15 arr[k] = L[i];
16 i++;
17 } else {
18 arr[k] = R[j];
19 j++;
20 }
21 k++;
22 }
23 while (i < n1)
24 arr[k++] = L[i++];
25 while (j < n2)
26 arr[k++] = R[j++];
27 }
28
29 public static void mergeSort(int arr[], int l, int r) {
30 if (l < r) {
31 int m = (l + r) / 2;
32 mergeSort(arr, l, m);
33 mergeSort(arr, m + 1, r);
34 merge(arr, l, m, r);
35 }
36 }
37
38 public static void main(String args[]) {
39 int arr[] = {12, 11, 13, 5, 6, 7};
40 mergeSort(arr, 0, arr.length - 1);
41 for (int i = 0; i < arr.length; ++i)
42 System.out.print(arr[i] + " ");
43 }
44}
45
This Java code implements the merge sort algorithm. The recursive method mergeSort is used to sort the array, and the merge method combines the sorted halves.
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.