AlgoTales · Roadmap

Sorting linked lists

Intermediate · 9 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Sorting a linked list with insertion sort means taking items one at a time and sliding each into the right spot of a growing sorted chain. It is simple, needs no extra space, and is quick when the list is small or almost in order already.

Practical use cases

  • Web app: A waiting list in order of arrival time. A clinic booking page keeps a small waiting list that must always show patients by arrival time. When a late entry arrives, it is slid into its correct place in the chain instead of re-sorting the whole list. With 30 people waiting, each insert is only a few steps.
  • Web app: Keeping a leaderboard nearly sorted. A quiz game updates scores every few seconds, and the board is already nearly in order. Only the players whose scores changed need to move up or down a few places. This is far cheaper than a full re-sort on every update.
  • System: Small lists inside bigger sorts. Many sorting routines switch to insertion for tiny pieces because it has almost no overhead. Sorting a hand of playing cards is the same idea: pick up one card at a time and slide it into the right place among the ones you already hold.

The story: Zoya's String of Name Cards

For the school annual day, Zoya had name-cards threaded on a string: roll numbers 4, 2, 5, 1, 3. "Please arrange them in order," said the teacher. In an array she would simply swap cards around, but threaded cards can't be swapped: each card holds only the string to the next card.

Zoya made two piles. The sorted pile started empty and the waiting string held everything. She took the first waiting card, walked along the sorted pile until she found the right gap, and tied the card in there by changing just two strings: the card before and the new card's own string. The other cards never moved.

Card by card, the sorted pile grew: 4, then 2 4, then 2 4 5, then 1 2 4 5, finally 1 2 3 4 5. Zoya was pleased that there was no extra string or table needed. She just re-tied existing knots.

That is insertion sort on a linked list. A fun surprise: with arrays, insertion sort must shift many elements to make room, but with a linked list inserting in the middle is cheap. The walk to find the gap still costs time, so it is O(n²) overall. For big lists we want something smarter, and the next lesson brings merge sort.

How to spot this problem, and where you need it

You keep a short or nearly ordered list and want to keep it sorted as items arrive, without the cost and complexity of a heavy sorting method.

Signs you need it

  • The list is small (dozens of items) or already mostly in order, and a full sort feels like overkill.
  • Items arrive one at a time and each must be put in the right place immediately.
  • You hold the data as a chain, so moving an item is just changing links rather than shifting a block of memory.

Where to use it in a project

  • Small waiting lists, priority lists and top-N boards that update frequently.
  • Final tidy-up stage after a bigger algorithm has left data nearly sorted.
  • Teaching code for pointer manipulation and stable sorting.

The solution

Start with an empty sorted chain. Take the next item from the unsorted chain. Walk through the sorted chain until you find the first item that is larger, then link the new item in just before it. Repeat for every item. When the unsorted chain is empty, the sorted chain is complete. Equal items keep their original order, which makes it a stable sort.

Payoff: Before: re-sorting the whole waiting list on every new arrival. After: a few link changes per arrival, and almost nothing for already ordered data.

Explain it like I am 8

You have a few cards in a messy line. Take them one at a time and slide each into the right spot in a tidy line you are building. The tidy line grows until all cards are in it.

How it works, step by step

  1. Make a dummy node. It starts the sorted list, which is empty at first.
  2. Take the first node (cur) out of the unsorted list; remember cur.next before changing anything.
  3. Walk from the dummy until p.next is bigger than cur (or the end).
  4. Insert: cur.next = p.next, then p.next = cur.
  5. Move to the next unsorted node. When none remain, return dummy.next.

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 insertionSort(?Node $head): ?Node {
    $dummy = new Node(0);                 // start of the sorted list (empty)
    $cur = $head;
    while ($cur !== null) {
        $nextWaiting = $cur->next;        // remember before we relink
        $p = $dummy;
        while ($p->next !== null && $p->next->val <= $cur->val) {   // find the gap (<= keeps it stable)
            $p = $p->next;
        }
        $cur->next = $p->next;            // tie the card in: two pointer changes
        $p->next = $cur;
        $cur = $nextWaiting;
    }
    return $dummy->next;
}

echo show(insertionSort(fromArray([4, 2, 5, 1, 3]))) . "\n";    // 1 -> 2 -> 3 -> 4 -> 5
echo show(insertionSort(fromArray([3, 3, 1]))) . "\n";          // 1 -> 3 -> 3

JavaScript

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 insertionSort(head) {
  const dummy = new Node(0);                // start of the sorted list (empty)
  let cur = head;
  while (cur !== null) {
    const nextWaiting = cur.next;           // remember before we relink
    let p = dummy;
    while (p.next !== null && p.next.val <= cur.val) {   // find the gap (<= keeps it stable)
      p = p.next;
    }
    cur.next = p.next;                      // tie the card in: two pointer changes
    p.next = cur;
    cur = nextWaiting;
  }
  return dummy.next;
}

console.log(show(insertionSort(fromArray([4, 2, 5, 1, 3]))));    // 1 -> 2 -> 3 -> 4 -> 5
console.log(show(insertionSort(fromArray([3, 3, 1]))));          // 1 -> 3 -> 3

Java

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 insertionSort(Node head) {
        Node dummy = new Node(0, null);       // start of the sorted list (empty)
        Node cur = head;
        while (cur != null) {
            Node nextWaiting = cur.next;      // remember before we relink
            Node p = dummy;
            while (p.next != null && p.next.val <= cur.val) {   // find the gap (<= keeps it stable)
                p = p.next;
            }
            cur.next = p.next;                // tie the card in: two pointer changes
            p.next = cur;
            cur = nextWaiting;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        System.out.println(show(insertionSort(fromArray(4, 2, 5, 1, 3))));    // 1 -> 2 -> 3 -> 4 -> 5
        System.out.println(show(insertionSort(fromArray(3, 3, 1))));          // 1 -> 3 -> 3
    }
}

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, " -> ")
}

func insertionSort(head *Node) *Node {
	dummy := &Node{} // start of the sorted list (empty)
	cur := head
	for cur != nil {
		nextWaiting := cur.next // remember before we relink
		p := dummy
		for p.next != nil && p.next.val <= cur.val { // find the gap (<= keeps it stable)
			p = p.next
		}
		cur.next = p.next // tie the card in: two pointer changes
		p.next = cur
		cur = nextWaiting
	}
	return dummy.next
}

func main() {
	fmt.Println(show(insertionSort(fromSlice([]int{4, 2, 5, 1, 3})))) // 1 -> 2 -> 3 -> 4 -> 5
	fmt.Println(show(insertionSort(fromSlice([]int{3, 3, 1}))))       // 1 -> 3 -> 3
}

Time: O(n²) worst case, O(n) if already sorted · Extra space: O(1). No shifting is needed (unlike an array), but finding each gap is still a walk.

Watch out for

  • Forgetting to save cur.next before relinking: you lose the rest of the unsorted list.
  • Walking from the head of the unsorted list instead of the sorted one, mixing the two.
  • Using < instead of <= in the gap search: the sort still works but equal items lose their original order (it is no longer stable).

Quick check

  1. What do we do first with the current node before inserting it?
    • Delete it
    • Save its next pointer so we do not lose the rest
    • Sort it
    • Reverse it
  2. Why is inserting in a linked list better than in an array here?
    • No searching is needed
    • It uses more memory
    • No elements have to shift to make room
    • It is always O(1) overall
  3. Worst-case time of insertion sort on a linked list?
    • O(n log n)
    • O(n)
    • O(log n)
    • O(n²)