Bottom Up Mergesort, Again.
Merge sort and linked lists go together quite well, even better than it does for arrays, where it's performance is still amongst the best. I have in the past covered bottom up mergre sorting algorithms, though each of those implementations have required additional storage in the form of an auxillary data structures, whittling away at what makes top-down merge sort so great for linked lists: it's O(1) space requirement.
In todays post I'm going to cover merge sorting a linked list from the bottom up without needing a secondary data structure, lets do it.
Mergesort, From the Bottom up
It may come as a surprise to some that both top-down and bottom-up merge sort have the same merge-tree but that the traversal order of said tree is what differntiates them. Bottom-up merge sort is inherently a breath-first traversal, while top-down explores the tree depth first.
for (int w = 1; w < n; w *= 2)
for (int b = 0; b < n-w; b += 2*w)
merge(a, aux, b, b+w, min(b+w+w, n));
Picture a merge tree for a top down mergesort. The root is the unsorted list, the second level is the two halfs of the unsorted list, etc until you get to the leaf level, where each list is one node long.
The actual sorting doesnt begin until we reach the leaf level, it is then we merge the singleton lists into ordered lists of two elements, then merge those lists into sorted 4-element lists, etc. as we work our way, ahem, *from the bottom, up to the root*, merging the sorted sublists until we have the complete sorted list. The following shows the result of each levels final state:
MERGESORT
M
E
R
G
E
S
O
R
T
E M
G R
E S
O R
T
E G M R
E O R S
T
EEGMORRST
Bottom up mergesort exploits this property by arranging the merges in a way that eliminates the need for the downward traversal, choosing instead to simply start at the leaves. When the length of the list is a power of two, the same set of sub-lists are merged, however they are merged in a different order.
1-by-1, then 2-by-2, then 4-by-4, etc.
When using mergesort for arrays we skip the top-down partitioning by trating single array entries as lists of size one, and combining them with their neighbor in sorted order to create lists of size 2. This is handled using nested loops, with the outer loop determining the current length of the list to be sorted, continuing until the length matches the size of the list. We can do something similar for linked lists, except how we handle the inner loop will be a bit different.
node* bumsort(node* h) {
int merges = 2;
for (int length = 1; merges > 1; length *= 2) {
merges = 0;
node d(-1, nullptr); node* c = &d;
while (h != nullptr) {
auto list = merge(takeN(&h, length), takeN(&h, length));
while (c->next) c = c->next;
merges++;
}
h = d.next;
}
return h;
}
takeN() is a simple method which removes the first N nodes from the list, returning the head of the old list while updating the head of the list being sorted by reference.
node* takeN(node** h, int N) {
auto x = *h;
auto starting = x;
int i = 1;
while (i < N && x != nullptr) {
x = x->next; i++;
}
*h = (x == nullptr) ? x:x->next;
if (x) x->next = nullptr;
return starting;
}
Some Bad News
Unfortunately, the algorithm we just put together is about twice as slow as the top-down variant in practice. Why? Cache locality, of course! but have no fear, there is a way we can salvage our bottom up mergesort while still keeping the cache lines hot. How might we do this you ask? By changing the traversal order of the merge tree, of course! But that's a post for another day.
-
Tail Call Optimization
-
Bottom Up Mergesort, Again.
-
Comparing Self-Balancing Search Trees
-
Collision Detection With Spatial Grid Partitioning
-
Keep Calm And Parse On: Error Handling for LR Parsers
-
From Finite Automata To A Lexical Analyzer
-
DFA Minimization: Moore's Algorithm
-
Parsing Regular Expressions with MGCPGen
-
Determinization: Converting εNFA to DFA
-
Implementing Lexical Scoping: Resolving Variable Names with De Bruijn Indices
Leave A Comment