Linked List Sort in Java
Learn how Linked List Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.
Introduction
Linked List Sort isn’t one algorithm but a question: how do you sort a linked list? A linked list has no index. Each node holds a value and a pointer to the next node, so getting to the tenth value means walking past the first nine. Sorts that jump around an array by index, such as QuickSort or heap sort, become slow on a list, and the techniques that work well are the ones that only ever walk forward.
Three ideas carry the topic:
- Nodes and links: the list is a chain of
Nodeobjects, each with avaland anextpointer; the first node is the head, and the last node points tonull. - Relinking versus copying: a list can be sorted by changing the
nextpointers so the nodes form a new order, or by copying the values into an array, sorting that, and writing the values back. - Merge sort fits lists best: splitting a list and merging two sorted lists only need forward walks and pointer changes, so merge sort sorts a list in $O(n \log n)$ without any extra array.
Sorting linked lists comes up in interviews and in systems that keep data in chains, such as free lists, hash-table buckets, or Java’s own LinkedList, whose sort method copies the values into an array, sorts the array, and writes them back.
This article follows the repository’s copy-to-array approach with three techniques: the values of the list are copied into an int array, sorted with merge sort, insertion sort or heap sort, and written back into the same nodes.
Performance Characteristics
With the copy approach, the list itself only costs three linear walks; the speed depends on the array technique that does the actual sorting.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Technique | Best | Average | Worst |
|---|---|---|---|
| Merge sort (option 1) | $O(n \log n)$ | $O(n \log n)$ | $O(n \log n)$ |
| Insertion sort (option 2) | $O(n)$ | $O(n^2)$ | $O(n^2)$ |
| Heap sort (option 3) | $O(n \log n)$ | $O(n \log n)$ | $O(n \log n)$ |
Why these? Counting the nodes, copying the values out and writing them back are three walks of $O(n)$ each, so the total is dominated by the sort in the middle: merge sort and heap sort are $O(n \log n)$ in every case, and insertion sort is $O(n^2)$, but $O(n)$ when the list is already sorted.
To sort the list without an extra array, use merge sort on the nodes themselves: find the middle with a slow and a fast pointer, cut the list in two, sort both halves recursively, and merge them by relinking
nextpointers. That runs in $O(n \log n)$ with only $O(\log n)$ extra space for the recursion, and a bottom-up version needs none at all.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n)$ for the array of values in all three techniques; merge sort also allocates merge buffers |
| In place | No (the values go out to an array and back); the nodes themselves never move |
| Stable | Not applicable here: the list holds plain int values, which can’t be told apart |
Algorithm (Pseudo Code)
The repository code starts by building a linked list from an input array: one node per value, each linked to the next. To sort it, it walks the list once to count the nodes, creates an array of that size, and walks the list again to copy the values into the array. Insertion sort does both at once: it inserts each value into its place in the array as it walks the list.
The array is then sorted with the chosen technique: merge sort, insertion sort or heap sort, exactly as on any array. Finally the list is walked a last time, and the sorted values are written back into the nodes, in order. The nodes and their links stay where they were; only the values inside them change, so the list now reads in sorted order from the head.
1
2
3
4
5
6
7
8
9
sortList(head, technique):
c = count(head) // walk 1: count the nodes
a = new int[c]
copy each node's val into a // walk 2 (insertion sort inserts here)
sort a with merge sort, insertion sort or heap sort
ptr = head
for i = 0 to c - 1: // walk 3: write the values back
ptr.val = a[i], ptr = ptr.next
return head
After the last walk, the node values, read from the head, are the sorted values, and the head is still the same node as before.
Because only values move, anything else stored in a node would stay behind with the node, attached to the wrong value. For lists of records, sort by relinking nodes, or move whole objects, not just keys.
Visualization
The visualization below follows the Java code step by step, starting with the values 0 to 9 in shuffled order.
Each step shows the linked list, the int array the values are copied into, and the line of code that is running, with a short explanation of what just happened:
- Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
- Play: press Play to run the steps automatically, and press it again to pause.
- Shuffle: press the shuffle button to start again with a new random order.
- Technique: choose merge sort (option 1), insertion sort (option 2) or heap sort (option 3) in the footer. The array steps follow that technique: one merge, one insertion or one heap extraction per step.
- List: each box is a node, with its value and, below it, its identity
#0to#9. The identities never move: at the end, the same nodes hold different values. - Colours: the node being read and the values being copied are amber, the values just changed in the array are salmon, and sorted values, in the array and back in the list, are green.
Java Code
The code lives in one file, LinkListSort.java, which holds five classes. LinkListSort has a public static method, isSorted, that builds a linked list from an array, sorts it with the chosen technique and checks the result, plus a compare helper. Node is the list node. Task, Task1 and Task2 hold the merge sort, insertion sort and heap sort techniques, each with its own count method. The classes don’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
LinkListSort.java.
isSorted
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public static boolean isSorted(int[] p, int option) {
int[] a = p;
int[] b = p;
int ch = option;
switch (ch) {
case 1:
Task nm = new Task();
Node start = null;
Node prev = null;
Node fresh;
Node ptr;
for (int i = 0; i < a.length; i++) {
fresh = new Node();
fresh.val = a[i];
if (start == null) {
start = fresh;
} else {
prev.next = fresh;
}
prev = fresh;
}
start = nm.sortByMergeSort(start);
int i = 0;
for (ptr = start; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
}
Arrays.sort(b);
LinkListSort uu = new LinkListSort();
return uu.compare(a, b);
// case 2 and case 3 build the list the same way and call
// sortByInsertionSort and sortByHeapSort instead
default:
System.out.println("Wrong choice");
}
return false;
}
isSorted is the entry point, shown here with only the first case; the other two are identical apart from the sorting call. It builds a linked list by creating one Node per value and linking each to the previous one, sorts the list, and copies the sorted values back into a. It then sorts b with Arrays.sort and compares the two. An unknown option prints “Wrong choice” and returns false.
aandbare not copies: both are the same array asp. Writing the sorted list intoatherefore sorts the caller’s array,Arrays.sort(b)sorts that same, already sorted array again, andcompare(a, b)compares the array with itself, soisSortedreturnstruefor options 1, 2 and 3 whatever the sort did. In case 2 the comment even says the result should befalse. Copying first, withint[] b = p.clone(), and comparing the sorted list against that copy would make the check meaningful; a method that sorts its argument would also deserve a name other thanisSorted.
Node and count
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Node {
int val;
Node next;
}
int count(Node head) {
int c = 0;
Node ptr;
for (ptr = head; ptr != null; ptr = ptr.next) {
c++;
}
return c;
}
Node is a minimal singly linked list node: an int value and a pointer to the next node, null at the end of the list. count walks the list from the head and counts the nodes, because a linked list doesn’t store its own length. Each of the three technique classes has its own copy of this method.
sortByMergeSort, task and task1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public Node sortByMergeSort(Node head) {
if (head == null || head.next == null) {
return head;
}
int c = count(head);
a = new int[c];
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
}
i = 0;
task(a, 0, c - 1);
for (Node ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
}
return head;
}
void task(int[] n, int i, int j) {
if (i < j) {
int m = (i + j) / 2;
task(n, i, m);
task(n, m + 1, j);
task1(n, i, m, j);
}
}
void task1(int[] n, int s, int m, int e) {
int i = s;
int k = 0;
int j = m + 1;
int[] b = new int[e - s + 1];
while (i <= m && j <= e) {
if (n[j] >= n[i]) {
b[k++] = n[i++];
} else {
b[k++] = n[j++];
}
}
while (i <= m) {
b[k++] = n[i++];
}
while (j <= e) {
b[k++] = n[j++];
}
for (int p = s; p <= e; p++) {
a[p] = b[p - s];
}
}
sortByMergeSort (class Task) counts the nodes, copies the values into the field a, sorts it with a top-down merge sort, and writes the values back into the nodes. task splits the range in half and recurses; task1 merges two sorted halves into a new buffer b, taking the left value first on a tie, and copies the buffer back.
Two details are worth noticing:
task1reads from its parameternbut writes the merged values to the fielda. It only works becausetaskis always called withaitself; passing any other array would merge into the wrong one. Writing back tonwould remove the trap.- A new buffer
bis allocated for every merge, so the technique allocates $O(n \log n)$ memory in total over the whole sort, on top of the array of values.
sortByInsertionSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public Node sortByInsertionSort(Node head) {
if (head == null || head.next == null) {
return head;
}
int c = count(head);
int[] a = new int[c];
a[0] = head.val;
int i;
Node ptr;
for (ptr = head.next, i = 1; ptr != null; ptr = ptr.next, i++) {
int j = i - 1;
while (j >= 0 && a[j] > ptr.val) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = ptr.val;
}
i = 0;
for (ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
}
return head;
}
sortByInsertionSort (class Task1) combines copying and sorting: it walks the list once, and inserts each value straight into its place in the growing sorted array, shifting larger values one position right, as in the Insertion Sort guide. A second walk writes the values back into the nodes.
sortByHeapSort, task and task1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public Node sortByHeapSort(Node head) {
if (head == null || head.next == null) {
return head;
}
int c = count(head);
int[] a = new int[c];
int i = 0;
for (Node ptr = head; ptr != null; ptr = ptr.next) {
a[i++] = ptr.val;
}
i = 0;
task(a);
for (Node ptr = head; ptr != null; ptr = ptr.next) {
ptr.val = a[i++];
}
return head;
}
void task(int[] n) {
int k = n.length;
for (int i = k / 2 - 1; i >= 0; i--) {
task1(n, k, i);
}
for (int i = k - 1; i > 0; i--) {
int d = n[0];
n[0] = n[i];
n[i] = d;
task1(n, i, 0);
}
}
void task1(int[] n, int k, int i) {
int p = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < k && n[l] > n[p]) {
p = l;
}
if (r < k && n[r] > n[p]) {
p = r;
}
if (p != i) {
int d = n[p];
n[p] = n[i];
n[i] = d;
task1(n, k, p);
}
}
sortByHeapSort (class Task2) copies the values into an array and runs a textbook heap sort on it: task builds a max-heap from the bottom up, then repeatedly swaps the largest value to the end and restores the heap with task1, a recursive sift-down. The values are written back into the nodes at the end. The Heap Sort guide covers the same steps on an array of objects.
Running it
1
2
3
4
int[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
boolean result = LinkListSort.isSorted(numbers, 1);
System.out.println(result + " " + Arrays.toString(numbers));
// true [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Call isSorted with an array and a technique, 1, 2 or 3. It returns true, and, as a side effect, the array itself comes back sorted. Node and the Task classes are package-private, so to sort a list of your own nodes directly, the code must be in the com.javanibble.sort package.
Summary
- Sorting a linked list is harder than sorting an array because there is no index; the good techniques only walk forward.
- This implementation copies the list’s values into an
intarray, sorts it with merge sort, insertion sort or heap sort, and writes the values back into the same nodes. - After the last walk, the nodes, read from the head, hold the values in sorted order; the nodes themselves and their links never change.
- The cost is that of the array technique: $O(n \log n)$ for merge and heap sort, $O(n^2)$ for insertion sort, plus $O(n)$ extra space for the array.
isSortedalways returnstrueand sorts its argument, so treat it as a demo, not a check. To sort a real linked list, use merge sort that relinks nodes, or Java’sLinkedList.sort.
