Sort List
Sort a linked list by merging ever longer sorted runs of nodes, without recursion or an extra array.
Given the headvalnextnull
Example 1
Output: [1, 2, 3, 4]
Example 2
Output: [-1, 0, 3, 4, 5]
Example 3
Output: []
The Idea
Sorting a hand of cards is easy when you can spread them out and pick up any card you like. A linked list does not let you do that. You hold only the first node, and you reach any other node by following next
So what can a linked list do cheaply? It can cut itself in two by setting one node's nextnull
Merging needs sorted lists to start with, so where do they come from? A list of one node is already sorted. Call a sorted stretch of nodes a run. Every node on its own is a run of length 1, and two runs of 1 merge into a run of 2. Look at the picture below.
The top row is Example 1, 4 -> 2 -> 1 -> 3, seen as four runs of 1. The first round merges [4] and [2] into 2, 4, and merges [1] and [3] into 1, 3. That gives the row labelled "after round 1": two sorted runs of 2. The second round merges run [2, 4] with run [1, 3], and the bottom row is the whole list in order.
Each round doubles the run length: 1, then 2, then 4, until one run covers the whole list. Sorting by merging ever larger sorted pieces is called merge sort. Starting from the smallest runs and working upward, as in the picture, is its bottom-up form.
The number of nodes does not have to be a power of two. Example 2 has five nodes, so in the first two rounds the last node, 0, has no partner run. It stays at the end, and the third round, with runs of 4, merges it with the other four nodes.
Solution Approach
Four decisions turn these rounds into code: why merge sort fits a linked list, how many rounds to run, how to cut and merge the runs of one round, and how to link the merged runs back into one list. The recursive form of merge sort is an optional alternative.
Why merge sort fits a linked list
Why not a simpler sort? The simplest way to sort a linked list takes the nodes one by one and walks from the head to find each one's place. For a list that is already in order, every node walks past all the nodes placed before it, so the work grows with n². Copying the values into an array and sorting that is fast, but the array takes memory for all n values, which the follow-up rules out.
Other fast sorts suit a list badly too. Heap sort keeps the values in an array shaped like a tree and keeps jumping between far-apart positions, which a list can only reach by walking. Quick sort splits the values around one chosen value, and on a list it can still take O(n²) time when those splits come out uneven. Merge sort only cuts lists and merges them, and both are cheap on a list.
Counting the rounds
When is the list sorted? As soon as one run is at least as long as the whole list. So first count the nodes into nsizesizen
Cutting and merging the runs of one round
How does one round find its runs? It walks the list from the front. It cuts off sizesize
The two runs are then merged, exactly as two sorted lists are in
Linking the merged runs back together
Where does each merged run go? Right after the run merged before it, so the list stays in one piece. A pointer tailtail
The very first run has no node in front of it. A spare node placed before the head, called a dummy node, solves that: the first merge attaches after the dummy, and the sorted list always starts at the dummy's next
Optional: the recursive version
Merge sort is often written top-down instead. Find the middle of the list with two pointers, one moving one node at a time and one moving two, cut the list there, sort each half with a recursive call, and merge the halves. That is shorter to write and also takes O(n log n) time.
Each recursive call that has not finished yet keeps a small record in memory, on the call stack. The halves get halved about log2 n times, so the stack holds up to about log2 n records. That memory grows with n, so it misses the follow-up's constant-memory goal, which the bottom-up rounds meet.
Java Solution
Here is what sortList
- First, walk the list once and count its nodes into
.n - Create a dummy node,
, whosedummy isnext .head - An outer loop runs the rounds, with
going 1, 2, 4 and so on while it is less thansize . Each round starts withn ontail anddummy on the first node of the list.rest - Inside, a
loop takes pairs of runs untilwhile isrest . The left run,null , starts atleft . The helperrest cuts it aftersplit(left, size) nodes and returns the next node, the start of the right run,size . A secondright cuts that run and movessplit(right, size) to what follows it.rest - The helper
links the smaller front node aftermerge(left, right, tail) again and again, then attaches whatever is left of the other run. It walks to the end of the merged run and returns that last node as the newtail .tail - After the last round, return
.dummy.next
The class also has a small ListNodebuildshow[1, 2, 3]main
public class SortList {
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode sortList(ListNode head) {
int n = 0;
for (ListNode p = head; p != null; p = p.next) {
n++;
}
ListNode dummy = new ListNode(0, head);
for (int size = 1; size < n; size *= 2) { // merge sorted runs of length size
ListNode tail = dummy;
ListNode rest = dummy.next;
while (rest != null) {
ListNode left = rest;
ListNode right = split(left, size); // left has size nodes
rest = split(right, size); // right has up to size nodes
tail = merge(left, right, tail); // append the merged run
}
}
return dummy.next;
}
// Cut the list after count nodes; return the start of the rest.
private static ListNode split(ListNode head, int count) {
for (int i = 1; head != null && i < count; i++) {
head = head.next;
}
if (head == null) {
return null;
}
ListNode rest = head.next;
head.next = null;
return rest;
}
// Merge two sorted lists after tail; return the new tail.
private static ListNode merge(ListNode a, ListNode b, ListNode tail) {
while (a != null && b != null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = (a != null) ? a : b;
while (tail.next != null) {
tail = tail.next;
}
return tail;
}
static ListNode build(int... values) {
ListNode head = null;
for (int i = values.length - 1; i >= 0; i--) {
head = new ListNode(values[i], head);
}
return head;
}
static String show(ListNode head) {
StringBuilder sb = new StringBuilder("[");
for (ListNode p = head; p != null; p = p.next) {
sb.append(p.val).append(p.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(sortList(build(4, 2, 1, 3))));
System.out.println(show(sortList(build(-1, 5, 3, 4, 0))));
System.out.println(show(sortList(build())));
System.out.println(show(sortList(build(7))));
System.out.println(show(sortList(build(3, 1, 3, 2, 1, 2, 1))));
System.out.println(show(sortList(build(6, 5, 4, 3, 2, 1))));
}
}
Running it prints:
[1, 2, 3, 4]
[-1, 0, 3, 4, 5]
[]
[7]
[1, 1, 1, 2, 2, 3, 3]
[1, 2, 3, 4, 5, 6]
Look at the second line, [-1, 0, 3, 4, 5]size[][7]ndummy.next
The line [1, 1, 1, 2, 2, 3, 3][1, 2, 3, 4, 5, 6]
The loop at the end of mergetailtailtail[2, 1, 3]
Complexity
The work is one counting walk, then a series of rounds that each walk the whole list.
- Time: O(n log n). The run length doubles every round, so the n nodes need about log2 n rounds, rounded up: three for the five nodes of Example 2. In each round,
andsplit together pass over every node a small, fixed number of times.merge - Space: O(1). The method keeps only a few pointers (
,dummy ,tail ,rest ,left ) and relinks the existing nodes. There is no array copy, and the rounds replace recursion, so no call stack grows with n.right
The same idea on an array, where merging needs a second array, is explained in