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)
1using System;
2
3class MergeSort {
4 public static void Merge(int[] arr, int l, int m, int r) {
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 int[] L = new int[n1];
8 int[] R = new int[n2];
9 Array.Copy(arr, l, L, 0, n1);
10 Array.Copy(arr, m + 1, R, 0, n2);
11 int i = 0, j = 0, k = l;
12 while (i < n1 && j < n2) {
13 if (L[i] <= R[j]) {
14 arr[k++] = L[i++];
15 } else {
16 arr[k++] = R[j++];
17 }
18 }
19 while (i < n1) arr[k++] = L[i++];
20 while (j < n2) arr[k++] = R[j++];
21 }
22
23 public static void MergeSortRec(int[] arr, int l, int r) {
24 if (l < r) {
25 int m = (l + r) / 2;
26 MergeSortRec(arr, l, m);
27 MergeSortRec(arr, m + 1, r);
28 Merge(arr, l, m, r);
29 }
30 }
31
32 static void Main() {
33 int[] arr = {12, 11, 13, 5, 6, 7};
34 MergeSortRec(arr, 0, arr.Length - 1);
35 Console.WriteLine(string.Join(" ", arr));
36 }
37}
38
This C# code implements merge sort using recursion. It splits the array into two halves, recursively sorts them and merges them back.
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.