Topological sorting with grouping support