




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)
1function merge(arr, left, mid, right) {
2    let n1 = mid - left + 1;
3    let n2 = right - mid;
4    let L = arr.slice(left, left + n1);
5    let R = arr.slice(mid + 1, mid + 1 + n2);
6    let i = 0, j = 0, k = left;
7    while (i < n1 && j < n2) {
8        if (L[i] <= R[j]) {
9            arr[k++] = L[i++];
10        } else {
11            arr[k++] = R[j++];
12        }
13    }
14    while (i < n1) {
15        arr[k++] = L[i++];
16    }
17    while (j < n2) {
18        arr[k++] = R[j++];
19    }
20}
21
22function mergeSort(arr, left, right) {
23    if (left < right) {
24        let mid = Math.floor((left + right) / 2);
25        mergeSort(arr, left, mid);
26        mergeSort(arr, mid + 1, right);
27        merge(arr, left, mid, right);
28    }
29}
30
31let nums = [5, 2, 3, 1];
32mergeSort(nums, 0, nums.length - 1);
33console.log(nums);The JavaScript solution applies the merge sort with a similar logic to Python, using the slice method for subarrays. The function mergeSort divides, and merge sorts the array in place.
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.