Google search did not yield any ideas or solutions neither did SO search.( One post existed with same title but different motive).
note: I can build one referring to exiting products build with to do this but knowing what is going to happen, how it should happen I will finish it sooner than other solutions.
Scope of this algorithm would be java script dependency manager, Family tree builder and many more things that may build tree or hierarchy structure from specification. For example taking javascript dependency manager here is how the algorithm would work.
Script a dependends
1. script b
2. script c.
and
Script b depends
1. Script x
2. Script y
and
Script x depends
1. Script J
so here is the order of loading the scripts
Script j
Script a
Script x, Script y
Script b
You are looking for topological sorting. You will find lots of information about this on the internet.