




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)
1using System;
2
3class MergeSort {
4    static void Merge(int[] array, int left, int mid, int right) {
5        int n1 = mid - left + 1;
6        int n2 = right - mid;
7        int[] leftArray = new int[n1];
8        int[] rightArray = new int[n2];
9        Array.Copy(array, left, leftArray, 0, n1);
10        Array.Copy(array, mid + 1, rightArray, 0, n2);
11        int i = 0, j = 0, k = left;
12        while (i < n1 && j < n2) {
13            if (leftArray[i] <= rightArray[j]) {
14                array[k++] = leftArray[i++];
15            } else {
16                array[k++] = rightArray[j++];
17            }
18        }
19        while (i < n1) {
20            array[k++] = leftArray[i++];
21        }
22        while (j < n2) {
23            array[k++] = rightArray[j++];
24        }
25    }
26
27    static void MergeSortRec(int[] array, int left, int right) {
28        if (left < right) {
29            int mid = left + (right - left) / 2;
30            MergeSortRec(array, left, mid);
31            MergeSortRec(array, mid + 1, right);
32            Merge(array, left, mid, right);
33        }
34    }
35
36    static void Main() {
37        int[] nums = {5, 2, 3, 1};
38        MergeSortRec(nums, 0, nums.Length - 1);
39        Console.WriteLine(string.Join(" ", nums));
40    }
41}In C#, merge sort is executed using MergeSortRec for recursive sorting, while Merge manages the order of elements between two halves. Array.Copy is used for splitting array subsections, making the process efficient.
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 C solution for quick sort uses Hoare's partition scheme, where we move indices inward until elements that should be swapped are found. The quickSort function recursively applies this process.