Sub topic 10
Sorting Linked Lists with Merge Sort
Earlier chapters sorted arrays. Merging two arrays needs a second buffer, because you can't slide elements into place without overwriting values you still need. Linked lists don't have this problem. A merge can relink the existing nodes into a new order without copying a single value. This makes merge sort the standard choice for sorting linked lists, and it changes the space analysis from the previous chapters.
This chapter assumes you know Python classes and references, recursion and the call stack, and the top-down merge sort and its O(n log n) analysis from earlier chapters.
Why Linked Lists Suit Merge Sort
A singly linked list is a chain of nodes. Each node holds a value and a reference to the next node. You can't jump to index i in constant time. You have to walk there from the head. This rules out or slows down most array sorting algorithms:
| Algorithm | What it needs | Fit for singly linked lists |
|---|---|---|
| Quicksort | Partitioning, good pivot choice (often random or median-of-three) | Works with a three-list partition, but random pivots cost O(n) to reach and the worst case is still O(n²) |
| Heapsort | Index arithmetic (`2i + 1`, `2i + 2`) | Poor: every parent/child jump costs O(n) |
| Insertion sort | Sequential scanning | Works, but O(n²) |
| Merge sort | Sequential scanning only | Excellent: split and merge both walk the list front to back |
Merge sort reads its input strictly left to right during the merge, and splitting only needs one walk to the midpoint. Both operations match what a linked list does cheaply.
The Node Class and Helpers
The code in this chapter uses a minimal node class plus two helpers that convert to and from Python lists, so you can test easily.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
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 outMerging by Relinking
The merge keeps a tail pointer to the last node of the output. At each step it attaches the smaller front node and advances. A dummy node (a placeholder with no meaningful value) sits in front of the output, so the first attachment needs no special case.
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.nextSeveral details matter here:
- No allocation besides the dummy. Every output node is an input node. The merge only rewrites
nextfields. - The leftover is attached in O(1). When one list runs out,
tail.next = a or bhangs the whole remainder of the other list on the end. An array merge has to copy the leftovers one by one. A linked list merge does not. - The tuple assignment is safe. In
tail.next, a = a, a.next, Python evaluates the right side first, so it captures the currentaanda.nextbefore any assignment. Then it setstail.nextand advancesa. If you split this into two statements in the wrong order (a = a.nextfirst), you lose the node. <=keeps the sort stable. On ties the node froma(the earlier half) goes first, exactly as in the array version.
Finding the Middle with Slow and Fast Pointers
To split a list in half without knowing its length, walk two pointers. slow moves one node per step and fast moves two. When fast reaches the end, slow is at the middle.
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))
print(to_list(sort_list(from_list([4, 2, 1, 3])))) # [1, 2, 3, 4]
print(to_list(sort_list(from_list([])))) # []
print(to_list(sort_list(from_list([5, 1, 5, 2, 1])))) # [1, 1, 2, 5, 5]slow ends on the last node of the first half. The line slow.next = None cuts the list into two independent lists. Both are then sorted recursively and merged.
Why `fast` Starts at `head.next`
This is the most common bug in linked-list merge sort. Suppose you start both pointers at head. Then take a two-node list A → B:
fast = A,fast.next = B, so the loop runs once:slow = B,fast = None.second = slow.next = None, and the first half is stillA → B.
The recursive call gets the same two-node list again, and it recurses forever until Python raises RecursionError. Starting fast one node ahead makes slow stop at A instead, which gives halves A and B. For even lengths this split is exactly in half. For odd lengths the first half gets one extra node. Both halves are always non-empty when the list has at least two nodes, and that guarantee is what makes the recursion terminate.
Cost Analysis
Time. Finding the middle walks half the list, which is O(n) per call. The merge is also O(n). So the recurrence is still T(n) = 2T(n/2) + O(n), and the total is O(n log n) in every case. The midpoint walk adds a constant factor that the array version avoids, because the array version computes len(items) // 2 in O(1).
Space. The recursive version allocates one dummy node per merge call. Each dummy becomes garbage as soon as its merge returns, so at most O(log n) dummies are alive at any moment. The real extra cost is the call stack: recursion depth is ⌈log₂ n⌉, so auxiliary space is O(log n). Compare that with the O(n) buffer an array merge sort needs. For a million nodes, the depth is about 20 frames, so Python's default recursion limit of 1000 doesn't come into play.
| Variant | Time | Auxiliary space | Stable |
|---|---|---|---|
| Array, top-down | O(n log n) | O(n) buffer + O(log n) stack | Yes |
| Linked list, top-down | O(n log n) | O(log n) stack | Yes |
| Linked list, bottom-up | O(n log n) | O(1) | Yes |
Bottom-Up on a Linked List: O(1) Extra Space
To remove the stack entirely, combine the bottom-up idea from the previous chapter with relinking. First count the length. Then make passes with run width 1, 2, 4, and so on. Each pass cuts off two runs of the current width, merges them, and appends the result to the growing output.
def split(head, n):
"""Cut the list after n nodes; return the head of the remainder."""
for _ in range(n - 1):
if head is None:
break
head = head.next
if head is None:
return None
rest = head.next
head.next = None
return rest
def merge_append(tail, a, b):
"""Merge a and b after tail; return the new tail."""
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
while tail.next:
tail = tail.next
return tail
def sort_list_bottom_up(head):
length = 0
node = head
while node:
length += 1
node = node.next
dummy = Node(None, head)
width = 1
while width < length:
tail = dummy
cur = dummy.next
while cur:
left = cur
right = split(left, width)
cur = split(right, width)
tail = merge_append(tail, left, right)
width *= 2
return dummy.next
print(to_list(sort_list_bottom_up(from_list([5, 2, 4, 6, 1, 3])))) # [1, 2, 3, 4, 5, 6]
print(to_list(sort_list_bottom_up(from_list([7])))) # [7]The only extra memory is a handful of pointer variables and one dummy node, so the space is O(1). merge_append has to walk to the end of the leftover run to find the new tail. That walk is still linear per pass, so each pass costs O(n), and there are ⌈log₂ n⌉ passes.
When right is None (an odd run at the end of a pass), merge_append just attaches left unchanged, and split(None, width) returns None. The loop then ends cleanly.
Edge Cases and Gotchas
- Empty and single-node lists return immediately from the base case. Always test both.
- Duplicates stay in their original relative order because both merges use
<=. If you write<, the sort is still correct but no longer stable. - Callers must use the return value. The original
headnode may now be in the middle of the sorted list. Writehead = sort_list(head), not justsort_list(head). - Other references go stale. Any outside variable pointing at a node still points at that node, but its neighbors have changed. Code that cached "the third node" will see a different position.
- Doubly linked lists work the same way. Sort using only
next, then make one final pass to repair theprevpointers. - Cache behavior is worse than with arrays, because nodes are scattered in memory. For a large list that you can afford to copy, copying the values into an array, sorting, and rebuilding is often faster in practice. Relinking wins when nodes are large, when nodes must keep their identity, or when memory is tight.
Exercise
Using the starting point slow, fast = head, head (instead of head.next for fast), trace sort_list on the list 1 → 2. What happens, and why?
Show answer
The loop runs once (fast.next is node 2), moving slow to node 2 and fast to None. Then second = slow.next = None and the first half is still 1 → 2. The recursive call receives the same two-node list, so the input never shrinks and Python eventually raises RecursionError. Starting fast at head.next makes slow stop at node 1, giving halves 1 and 2.
Exercise
Build nodes with values that compare by a key but carry a label, for example (2,'a'), (1,'b'), (2,'c'), (1,'d'), and sort by the first component. What output order does sort_list produce if the comparisons use only the key, and which line guarantees it?
Show answer
(1,'b'), (1,'d'), (2,'a'), (2,'c'). Equal keys keep their input order because the merge uses a.value <= b.value (comparing keys), which takes the node from the earlier half on ties.
Exercise
The recursive linked-list version needs no auxiliary array, yet it is not O(1) space. What does it use, how large is it for n = 1,000,000, and how does the bottom-up version avoid it?
Show answer
It uses the call stack, with depth ⌈log₂ n⌉, which is about 20 frames for a million nodes, so O(log n) space. The bottom-up version replaces recursion with a loop over run widths 1, 2, 4, …, keeping only a constant number of pointers, so its auxiliary space is O(1).