Description: Divides the list into smaller sublists, sorts them, and merges them back together.
Time Complexity: O(n log n)
Space Complexity: O(n)
Use Case: Suitable for large datasets.
Example Code:
python
defmerge_sort(arr): iflen(arr) <= 1: return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:]) return merge(left, right)
defmerge(left, right):
result = []
i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]:
result.append(left[i])
i += 1 else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:]) return result
Description: Selects a pivot element and partitions the array around it, sorting the partitions recursively.
Time Complexity: O(n log n)
Space Complexity: O(log n) (in-place version)
Use Case: Efficient for large datasets.
Example Code:
python
defquick_sort(arr): iflen(arr) <= 1: return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot] return quick_sort(left) + middle + quick_sort(right)