Would be better to use an actual topological sort, which would have the additional benefit of identifying cycles.