Sorting & Selection Hard
Linked List Merge Sort
Top-down merge sort finds a midpoint with slow and fast pointers, cuts the chain, recursively sorts both halves, and merges by relinking the original nodes.
Trace input
Bounded JSONEdit the lesson input, then build a deterministic source-linked trace.
Source scenarios
Complexity
BestO(N log N)
AverageO(N log N)
WorstO(N log N)
SpaceO(log N) recursion + O(1) live dummy; O(N) sentinels allocated cumulatively
Array state
Follow the active comparisons and writes.
Current operation
Trace stateReady to explore
Source behavior & common mistakes
Follow the recursive split and stable merge. On equal values, the merge takes the left chain first. Each merge also allocates a temporary dummy sentinel, while all sorted data nodes retain their original identities.
- slow advances one link while fast advances two; splitting this way keeps recursion depth O(log N).
- The source saves second = slow.next before setting slow.next to null, which cuts the two chains cleanly.
- During merge, <= chooses from the left chain first, preserving relative order for equal values.
- The source relinks existing data nodes and leaves size unchanged; it does allocate a temporary dummy Node for every merge call.
- Duplicate values are distinct nodes in the trace; stable order means their original input identities remain in order.
- Integer comparisons use relational operators, so signed 32-bit extremes do not overflow during sorting.
Algorithm code
JavaSortLinkedList.javaStep linked
The highlighted line follows the current step.
Ready to begin
Press Play to see what happens.
Detailed execution
Snapshot 1 / 1
Comparisons 0 · Writes 0