Your comparison algorithm seems to be: "compare groups by end date, except if they have the same start date, in which case ignore the end date and treat them as equal".  Is that actually what you're going for?  In any case, a comment above explaining what this function does would be good.