How to sort a list so that managers are always ahead of their subordinates
Posted
by James Black
on Stack Overflow
See other posts from Stack Overflow
or by James Black
Published on 2010-03-08T01:23:00Z
Indexed on
2010/03/08
1:35 UTC
Read the original article
Hit count: 427
I am working on a project using Groovy, and I would like to take an array of employees, so that no manager follows their subordinates in the array. The reason being that I need to add people to a database and I would prefer not to do it in two passes.
So, I basically have:
<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>
So, it should be sorted as such:
employeeid = 1
employeeid = 3
employeeid = 12
The first person should have a null for managers.
I am thinking about a binary tree representation, but I expect it will be very unbalanced, and I am not certain the best way to do this using Groovy properly.
Is there a way to do this that isn't going to involve using nested loops?
© Stack Overflow or respective owner