List Merge Sort
void List::Sort()
{
Link * currSeg, * nextSeg; // ptrs to sub-lists to be merged
segSize = 1;
do
{
numMerges = 0;
// merge all adjacent pairs of sub-lists of length segSize
currSeg = firstLink;
while (currSeg != 0)
{
nextSeg = currSeg;
advance nextSeg segSize steps in the list // Notes 1-3
merge the sublist at currSeg with the sublist at nextSeg // Note 4
(leaving currSeg at the beginning of the next segment)
++numMerges;
}
// double the sub-list size to be merged
segSize = 2 * segSize;
}
while (numMerges > 1); // stop when only 1 merge has occured - the last merge
take care of remainders
fix list at ends
}
- Finding next segment requires loop of nextSeg = nextSeg->nextLink
- Tradeoff runtime of pointer advance with runspace
- Total pointer advance contribution <= O(n log n)
- This follows the same algorithm as g_set_merge
- One step for each link in each segment
- List::MergeSort is stable, in-place, with runtime = Θ(n log n)