| | | | | |

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
}
  1. Finding next segment requires loop of nextSeg = nextSeg->nextLink
  2. Tradeoff runtime of pointer advance with runspace
  3. Total pointer advance contribution <= O(n log n)
  4. This follows the same algorithm as g_set_merge
  5. One step for each link in each segment
  6. List::MergeSort is stable, in-place, with runtime = Θ(n log n)

| | Top of Page | 8. Sorting Algorithms - 10 of 16