Sub topic 10
Sorting Linked Lists with Merge Sort
This chapter assumes you already know the top-down merge sort from earlier chapters and its O(n) auxiliary space cost for arrays. It also assumes you are comfortable with singly linked lists, where each node holds a value and a reference to the next node.
Why Linked Lists Suit Merge Sort
Array merge sort needs an extra buffer because the merge step writes elements into new positions. A linked list has no fixed positions. A node's place in the list is set by the next references pointing to it, so the merge can reorder nodes by changing those references. It never copies values into a second array.
Linked lists also handle other sorts badly. Quicksort and heapsort rely on random access, meaning they jump straight to index i in constant time. In a linked list, reaching index i means walking i nodes. Merge sort only reads each list from front to back, and a linked list does that well.
| Operation | Array | Singly linked list |
|---|---|---|
| Access element `i` | O(1) | O(i) |
| Find midpoint | O(1) | O(n) with slow/fast pointers |
| Merge two sorted runs | O(n) time, O(n) buffer | O(n) time, O(1) extra |
| Total auxiliary space | O(n) + O(log n) stack | O(log n) stack |
Finding the Midpoint
You can't compute len // 2 and jump to the middle, so the code uses two pointers. slow moves one node per step and fast moves two. When fast reaches the end, slow is at the middle. Cutting slow.next to None splits the list into two separate lists.
Finding the midpoint takes O(n) time per level of recursion. The merge at each level is already O(n), so the total stays O(n log n).
The Implementation
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def merge_lists(a, b):
dummy = tail = Node(None)
while a and b:
if a.value <= b.value:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b
return dummy.next
def sort_list(head):
if head is None or head.next is None:
return head
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
second = slow.next
slow.next = None
return merge_lists(sort_list(head), sort_list(second))
def from_list(values):
head = None
for v in reversed(values):
head = Node(v, head)
return head
def to_list(head):
out = []
while head:
out.append(head.value)
head = head.next
return out
print(to_list(sort_list(from_list([4, 2, 3, 1, 5])))) # [1, 2, 3, 4, 5]Some details in this code:
- The
dummynode givestaila starting point, so the first appended node needs no special case. The function returnsdummy.next, which skips the dummy. tail.next = a or battaches whatever remains of the unfinished list in one step. No loop is needed because those nodes are already linked in order.- The
<=comparison takes from the left list on ties, so the sort stays stable, just like the array version.
Common Errors
- Forgetting
slow.next = Noneleaves the first half still linked to the second half, so the recursion never shrinks. - Ignoring the return value of
sort_listis a bug. The oldheadmay now sit in the middle of the list, so always use the returned head. - Recursion depth is about log₂ n. For very long lists that is still small, but a bottom-up version that merges runs of width 1, 2, 4, and so on brings the stack space down to O(1).
Exercise
Trace sort_list on a two-node list 5 → 3 with fast starting at head.next. What are the two halves, and what does the merge return?
Show answer
slow is node 5 and fast is node 3. Because fast.next is None, the loop does not run. second is node 3, and setting slow.next = None cuts the list into 5 and 3. Each half is a single node and comes back unchanged. The merge compares 5 <= 3, which is false, so it takes 3 first, then attaches 5. The result is 3 → 5.
Exercise
Why is the auxiliary space of linked-list merge sort O(log n) and not O(1)?
Show answer
The merge uses only a constant number of pointers. The recursion is still about log₂ n calls deep, and each call keeps a stack frame, so the call stack uses O(log n) space.