Merge sort on linked lists
Advanced · 12 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Merge sort on a chain splits the chain into halves, sorts each half the same way, and merges the two sorted halves. It stays fast on big data and suits chains well, because merging only relinks items and needs no extra memory.
Practical use cases
- Web app: Sorting a huge order list by date. An admin exports 500,000 orders held as a chain and wants them by date. Simple sorting methods would take very long, while merge sort splits the problem into small ordered pieces and zips them together. The export finishes in seconds and gives the same date order every time.
- Web app: Stable sort for a product table. A shop lists products sorted by price, but products with equal prices must stay in the order of the earlier sort, such as by name. Merge sort is stable, so equal items are never swapped. The table looks predictable when users change sort columns.
- System: Database engines and external sorting. When data is too big for memory, databases sort pieces separately and merge the sorted pieces. This is the same split, sort and merge idea, and it is a main reason merge sort is used inside real systems that handle files much larger than the available memory.
The story: Sorting the Sweet Boxes
Diwali was near, and Mira's kirana store had a long chain of sweet boxes, each tied to the next, with prices that were all jumbled. Papa wanted them sorted cheapest to costliest before customers arrived. Insertion sort worked, but with hundreds of boxes it took all afternoon!
Mira remembered how two sorted queues could be merged quickly. "If I could get two sorted halves, merging would take one pass. And to sort each half... I can do the same trick again!" Cut the chain in half, ask two helpers to sort each half, then merge. And each helper cuts their half in half, and so on.
Where does it stop? When a chain has only one box, it is already sorted, and there is nothing to do. Then the merges happen on the way back, building sorted chains of 2, then 4, then everything. To cut the chain in half without counting, Mira used the slow and fast walkers from the lane.
This is merge sort for linked lists: split (slow/fast), sort each half (recursion), merge (two sorted lists). It runs in O(n log n) and, unlike arrays, needs no extra memory for merging because we just relink nodes. That makes it the favourite way to sort a linked list; it also is stable.
How to spot this problem, and where you need it
You must sort a large list that is stored as a chain, and you want predictable speed and a stable result without needing random access to elements.
Signs you need it
- Your data is a linked list or a stream of records, so quick-sort tricks that jump around by index do not apply.
- Sorting has to be stable: rows with the same key must keep their earlier relative order.
- The data is too big for memory or is processed in chunks and each chunk can be sorted then combined.
Where to use it in a project
- Sorting large exports, reports and logs by date, price or id.
- Multi-column sorting in tables where earlier orderings must be preserved.
- Big-data and database jobs that sort chunks and merge them.
The solution
If the chain has zero or one item it is already sorted. Otherwise find the middle, cut the chain in two, sort each half with the same method, and merge the two sorted halves by repeatedly taking the smaller front item. Since each level of splitting handles every item once and there are only about 20 levels for a million items, the total work stays small.
Payoff: Before: a simple sort taking a very long time on 500,000 records. After: about 20 passes over the data, finishing in seconds.
Explain it like I am 8
To sort a big messy pile: split it in two, give each half to a friend who does the same, and when the friends hand back two neat sorted piles, you zip them together. A pile of one card is already sorted, which stops the splitting.
How it works, step by step
- Base case: if the list is empty or has one node, it is already sorted, so return it.
- Split: use slow and fast pointers to find the end of the first half, then cut the link there. Now you have two lists.
- Sort each half by calling the same function on it (recursion).
- Merge the two sorted halves with the merge routine from the earlier lesson.
- Return the merged head. Each level touches every node once, and there are about log n levels.
The code in four languages
PHP
<?php
class Node {
public $val;
public ?Node $next = null;
public function __construct($val, ?Node $next = null) { $this->val = $val; $this->next = $next; }
}
function fromArray(array $vals): ?Node {
$head = null;
foreach (array_reverse($vals) as $v) { $head = new Node($v, $head); }
return $head;
}
function show(?Node $head): string {
$out = [];
for ($c = $head; $c !== null; $c = $c->next) $out[] = $c->val;
return implode(' -> ', $out);
}
function merge(?Node $a, ?Node $b): ?Node { // merge two sorted lists
$dummy = new Node(0);
$tail = $dummy;
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;
return $dummy->next;
}
function mergeSort(?Node $head): ?Node {
if ($head === null || $head->next === null) return $head; // 0 or 1 node: already sorted
$slow = $head; // find the end of the first half
$fast = $head->next;
while ($fast !== null && $fast->next !== null) {
$slow = $slow->next;
$fast = $fast->next->next;
}
$second = $slow->next; // second half starts here
$slow->next = null; // cut the chain in two
return merge(mergeSort($head), mergeSort($second));
}
echo show(mergeSort(fromArray([5, 2, 8, 1, 9, 3]))) . "\n"; // 1 -> 2 -> 3 -> 5 -> 8 -> 9
echo show(mergeSort(fromArray([7]))) . "\n"; // 7JavaScript
class Node {
constructor(val, next = null) { this.val = val; this.next = next; }
}
function fromArray(vals) {
let head = null;
for (let i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
return head;
}
function show(head) {
const out = [];
for (let c = head; c !== null; c = c.next) out.push(c.val);
return out.join(' -> ');
}
function merge(a, b) { // merge two sorted lists
const dummy = new Node(0);
let tail = dummy;
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;
return dummy.next;
}
function mergeSort(head) {
if (head === null || head.next === null) return head; // 0 or 1 node: already sorted
let slow = head; // find the end of the first half
let fast = head.next;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
}
const second = slow.next; // second half starts here
slow.next = null; // cut the chain in two
return merge(mergeSort(head), mergeSort(second));
}
console.log(show(mergeSort(fromArray([5, 2, 8, 1, 9, 3])))); // 1 -> 2 -> 3 -> 5 -> 8 -> 9
console.log(show(mergeSort(fromArray([7])))); // 7Java
import java.util.*;
public class Main {
static class Node {
int val;
Node next;
Node(int val, Node next) { this.val = val; this.next = next; }
}
static Node fromArray(int... vals) {
Node head = null;
for (int i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head);
return head;
}
static String show(Node head) {
StringJoiner out = new StringJoiner(" -> ");
for (Node c = head; c != null; c = c.next) out.add(String.valueOf(c.val));
return out.toString();
}
static Node merge(Node a, Node b) { // merge two sorted lists
Node dummy = new Node(0, null);
Node tail = dummy;
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;
return dummy.next;
}
static Node mergeSort(Node head) {
if (head == null || head.next == null) return head; // 0 or 1 node: already sorted
Node slow = head; // find the end of the first half
Node fast = head.next;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
Node second = slow.next; // second half starts here
slow.next = null; // cut the chain in two
return merge(mergeSort(head), mergeSort(second));
}
public static void main(String[] args) {
System.out.println(show(mergeSort(fromArray(5, 2, 8, 1, 9, 3)))); // 1 -> 2 -> 3 -> 5 -> 8 -> 9
System.out.println(show(mergeSort(fromArray(7)))); // 7
}
}Go
package main
import (
"fmt"
"strings"
)
type Node struct {
val int
next *Node
}
func fromSlice(vals []int) *Node {
var head *Node
for i := len(vals) - 1; i >= 0; i-- {
head = &Node{val: vals[i], next: head}
}
return head
}
func show(head *Node) string {
var out []string
for c := head; c != nil; c = c.next {
out = append(out, fmt.Sprint(c.val))
}
return strings.Join(out, " -> ")
}
// merge combines two sorted lists.
func merge(a, b *Node) *Node {
dummy := &Node{}
tail := dummy
for a != nil && b != nil {
if a.val <= b.val {
tail.next = a
a = a.next
} else {
tail.next = b
b = b.next
}
tail = tail.next
}
if a != nil {
tail.next = a
} else {
tail.next = b
}
return dummy.next
}
func mergeSort(head *Node) *Node {
if head == nil || head.next == nil { // 0 or 1 node: already sorted
return head
}
slow := head // find the end of the first half
fast := head.next
for fast != nil && fast.next != nil {
slow = slow.next
fast = fast.next.next
}
second := slow.next // second half starts here
slow.next = nil // cut the chain in two
return merge(mergeSort(head), mergeSort(second))
}
func main() {
fmt.Println(show(mergeSort(fromSlice([]int{5, 2, 8, 1, 9, 3})))) // 1 -> 2 -> 3 -> 5 -> 8 -> 9
fmt.Println(show(mergeSort(fromSlice([]int{7})))) // 7
}Time: O(n log n) · Extra space: O(log n). The only extra space is the recursion stack, about log n deep, because merging just relinks existing nodes.
Watch out for
- Not cutting the chain (
slow.next = null) before recursing, so the first half still points into the second and the recursion never shrinks. - Starting
fast = headfor the split: with two nodes the first half would be empty or the whole list, causing endless recursion. Starting athead.nextmakes the first half at least one node. - Forgetting the base case for empty and single-node lists.
Quick check
- How do we find the middle to split the list?
- Count all nodes first, always
- Slow and fast pointers
- Sort it first
- Reverse it
- What stops the recursion?
- Sorting by value
- A list with a null head only
- A list of zero or one node, already sorted
- Reaching the tail twice
- Time complexity of merge sort on a linked list?
- O(n²)
- O(n)
- O(log n)
- O(n log n)