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 <stdio.h>
2
3void merge(int arr[], int l, int m, int r) {
4 int i, j, k;
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 int L[n1], R[n2];
8 for (i = 0; i < n1; i++)
9 L[i] = arr[l + i];
10 for (j = 0; j < n2; j++)
11 R[j] = arr[m + 1 + j];
12 i = 0;
13 j = 0;
14 k = l;
15 while (i < n1 && j < n2) {
16 if (L[i] <= R[j]) {
17 arr[k] = L[i];
18 i++;
19 }
20 else {
21 arr[k] = R[j];
22 j++;
23 }
24 k++;
25 }
26 while (i < n1) {
27 arr[k] = L[i];
28 i++;
29 k++;
30 }
31 while (j < n2) {
32 arr[k] = R[j];
33 j++;
34 k++;
35 }
36}
37
38void mergeSort(int arr[], int l, int r) {
39 if (l < r) {
40 int m = l + (r - l) / 2;
41 mergeSort(arr, l, m);
42 mergeSort(arr, m + 1, r);
43 merge(arr, l, m, r);
44 }
45}
46
47int main() {
48 int arr[] = {12, 11, 13, 5, 6, 7};
49 int arr_size = sizeof(arr) / sizeof(arr[0]);
50 mergeSort(arr, 0, arr_size - 1);
51 for (int i = 0; i < arr_size; i++)
52 printf("%d ", arr[i]);
53 return 0;
54}
55
This C code implements the merge sort algorithm using a divide and conquer approach. It recursively breaks down the array into two halves, sorts them, and then merges 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)
1using System;
2
class HeapSort {
public void Heapify(int[] arr, int n, int i) {
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
Heapify(arr, n, largest);
}
}
public void Sort(int[] arr) {
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--)
Heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
Heapify(arr, i, 0);
}
}
static void Main() {
int[] arr = {12, 11, 13, 5, 6, 7};
HeapSort hs = new HeapSort();
hs.Sort(arr);
Console.WriteLine(string.Join(" ", arr));
}
}
This C# code employs heap sort by creating a binary heap and extracting the largest element to sort the array iteratively.