sort + group by aggregation algorithm