Improve implementation of sortAcrossGroups