




Sponsored
Sponsored
Merge Sort is a classic divide-and-conquer sorting algorithm that works in O(nlog(n)) time complexity and requires extra space proportional to the length of the array. The core concept is to divide the array into two halves, recursively sort each half, and then merge the sorted halves to produce a sorted array.
Time Complexity: O(nlog(n))
Space Complexity: O(n) (for temporary arrays used during merging)
1#include <stdio.h>
2
3void merge(int arr[], int left, int mid, int right) {
4    int n1 = mid - left + 1;
5    int n2 = right - mid;
6    int L[n1], R[n2];
7    for (int i = 0; i < n1; i++)
8        L[i] = arr[left + i];
9    for (int j = 0; j < n2; j++)
10        R[j] = arr[mid + 1 + j];
11    int i = 0, j = 0, k = left;
12    while (i < n1 && j < n2) {
13        if (L[i] <= R[j]) {
14            arr[k] = L[i];
15            i++;
16        } else {
17            arr[k] = R[j];
18            j++;
19        }
20        k++;
21    }
22    while (i < n1) {
23        arr[k] = L[i];
24        i++;
25        k++;
26    }
27    while (j < n2) {
28        arr[k] = R[j];
29        j++;
30        k++;
31    }
32}
33
34void mergeSort(int arr[], int left, int right) {
35    if (left < right) {
36        int mid = left + (right - left) / 2;
37        mergeSort(arr, left, mid);
38        mergeSort(arr, mid + 1, right);
39        merge(arr, left, mid, right);
40    }
41}
42
43int main() {
44    int nums[] = {5, 2, 3, 1};
45    int length = sizeof(nums) / sizeof(nums[0]);
46    mergeSort(nums, 0, length - 1);
47    for (int i = 0; i < length; i++)
48        printf("%d ", nums[i]);
49    return 0;
50}The C solution uses the merge sort algorithm, implementing both the merge and mergeSort functions. The array is recursively split into halves, sorted, and merged. Extra arrays L and R are used for the merge process, ensuring the correct elements are compared and copied back to the original array.
Quick Sort is an efficient, in-place sorting algorithm that works in average O(nlog(n)) time complexity. This approach involves selecting a 'pivot' element from the array and partitioning the remaining elements into two subarrays according to whether they are less than or greater than the pivot. The subarrays are then sorted recursively.
Time Complexity: O(n2) in the worst case, O(nlog(n)) on average.
Space Complexity: O(log(n)) for recursive stack space.
1
The Java solution implements Hoare's partition scheme quick sort. It efficiently manages in-place partitions and recursive sorting through the quickSort and partition methods.