




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)
1def merge(arr, left, mid, right):
2    n1 = mid - left + 1
3    n2 = right - mid
4    L = arr[left:left + n1]
5    R = arr[mid + 1:mid + 1 + n2]
6    i = j = 0
7    k = left
8    while i < n1 and j < n2:
9        if L[i] <= R[j]:
10            arr[k] = L[i]
11            i += 1
12        else:
13            arr[k] = R[j]
14            j += 1
15        k += 1
16    while i < n1:
17        arr[k] = L[i]
18        i += 1
19        k += 1
20    while j < n2:
21        arr[k] = R[j]
22        j += 1
23        k += 1
24
25def merge_sort(arr, left, right):
26    if left < right:
27        mid = (left + right) // 2
28        merge_sort(arr, left, mid)
29        merge_sort(arr, mid + 1, right)
30        merge(arr, left, mid, right)
31
32nums = [5, 2, 3, 1]
33merge_sort(nums, 0, len(nums) - 1)
34print(nums)The Python version implements merge sort smoothly with Python's slicing and operations. The recursive function merge_sort splits and calls merge to organize the sections of the list during the sort process.
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.