Sub topic 14
Auxiliary space of common sorting algorithms
This chapter assumes you know Big O notation, the difference between input space and auxiliary space, and how recursion uses the call stack. Here we apply those ideas to sorting. Two algorithms with the same running time can differ a lot in the extra memory they need.
What to count
Auxiliary space is the memory an algorithm uses beyond the input itself. For sorting, that means temporary arrays, the recursion stack, and a few index or swap variables. The input array does not count, even when the algorithm rearranges it.
Comparison of common sorts
| Algorithm | Auxiliary space | Where the memory goes |
|---|---|---|
| Insertion sort | O(1) | One saved element and an index |
| Selection sort | O(1) | Two indices and a swap |
| Heap sort | O(1) | Heap is built inside the input array |
| Merge sort (array) | O(n) | Temporary array for merging |
| Quick sort | O(log n) average, O(n) worst | Recursion stack |
Merge sort: O(n) from the merge buffer
Merge sort splits the list in half, sorts each half, and merges the results. The merge step needs somewhere to write the combined output, so it allocates a new list.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
print(merge_sort([5, 2, 9, 1, 5, 6]))At any moment, the live buffers along one path of the recursion hold about n + n/2 + n/4 + ... elements, which is O(n). The recursion depth is O(log n), and that stack is smaller than the buffers, so O(n) dominates. The slices a[:mid] and a[mid:] are also copies, a hidden cost covered earlier.
Quick sort: the stack decides
In-place quick sort partitions by swapping elements inside the array, so it needs no merge buffer. Its only extra memory is the recursion stack. That stack depth depends on how balanced the splits are.
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)
data = [5, 2, 9, 1, 5, 6]
quick_sort(data)
print(data)With balanced splits, the depth is about log n. With a bad pivot, such as the last element of an already sorted list, each call peels off one element and the depth reaches n, so the worst case is O(n) space.
Python's built-in sorts
list.sort() and sorted() use Timsort, a merge-based algorithm. It needs up to O(n) temporary space, though it often uses less when the data is partly ordered. Also, sorted() returns a new list, which adds O(n) for the result itself. list.sort() sorts in place and avoids that copy.
Choosing by memory
- Memory is tight and the worst-case time must be guaranteed: heap sort gives O(1) space and O(n log n) time.
- You need a stable sort and have the memory: merge sort or Timsort.
- You want a fast general-purpose in-place sort: quick sort, with care over the recursion depth.
Exercise
Why is the auxiliary space of quick sort O(n) in the worst case even though it never allocates a second array?
Show answer
Each recursive call adds a stack frame. If every partition is badly unbalanced, the recursion goes n levels deep, and n frames are alive at once, which is O(n) space.
Exercise
A teammate says sorted(nums) and nums.sort() have the same space cost because both use Timsort. Is that correct?
Show answer
No. Both may use up to O(n) temporary space inside Timsort, but sorted(nums) also builds a new list of n elements for its result. nums.sort() reuses the input list.