Mostly unrelated to this change itself, but looks like getSortedElements, could call sortElements and avoid some duplicated code in this area.