algorithm - How do a topological sort in Groovy, or an FP language 如何对列表进行排序,以便经理始终领先于下属(How do I do a topological sort in Groovy, or an FP language)

标签 algorithm sorting groovy

我正在使用 Groovy 进行一个项目,我想采用一个员工数组,这样在数组中没有经理跟随他们的下属。原因是我需要将人员添加到数据库中,我不希望分两次完成。

所以,我基本上有:

<employees>
  <employee>
     <employeeid>12</employeeid>
     <manager>3</manager>
  </employee>   
  <employee>
     <employeeid>1</employeeid>
     <manager></manager>
  </employee>   
  <employee>
     <employeeid>3</employeeid>
     <manager>1</manager>
  </employee>   
</employees>

所以,它应该这样排序:

employeeid = 1
employeeid = 3
employeeid = 12

对于经理,第一个人应为空。

我正在考虑二叉树表示,但我预计它会非常不平衡,而且我不确定正确使用 Groovy 执行此操作的最佳方法。

有没有一种不涉及使用嵌套循环的方法来做到这一点?

最佳答案

http://en.wikipedia.org/wiki/Topological_sorting

假设除 CEO 以外的每个员工都有一个经理,我会将所有员工记录插入一个关联结构,该结构将每个员工 ID 映射到他们的直接下属列表。现在我们对 CEO 调用以下递归过程:

def recursiveinsert(e):
    insert e into the database
    for each direct report d of e:
        recursiveinsert(d)

关于algorithm - How do a topological sort in Groovy, or an FP language 如何对列表进行排序,以便经理始终领先于下属(How do I do a topological sort in Groovy, or an FP language),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2398781/

相关文章:

c# - 用于自定义排序列表的 Lambda 表达式

algorithm - 这个 "incremental sort"的时间复杂度

Jenkins 转义 sed 命令

multithreading - 使用Spock测试线程并发

dictionary - 无法在 Jenkins Pipeline 中使用 Groovy 迭代 Map

c++ - 求 O(1) 表示法中数字列表的平均值 - 常数时间

algorithm - 汉诺塔 - 替代解决方案

python - 根据字符串列表对列表列表进行排序

algorithm - 如何将 float 转换为分数?

php - 在数据集中找到最真实的市场平均价格的算法