in reply to Adding Special Rules to Sort

This isn't really a sorting problem, but a graph analysis problem. It may help to better understand this problem if you draw a diagram with circles representing the teams and arrows between the circles indicating who won (e.g. team to which arrow points is the winner).

When you do this you will probably see a big spagetti mess, so try to rearrange the circles and lines so that any circle (team) that has only outgoing arrows (e.g. is always the looser) is on the edge of the graph.

My guess is that you will quickly see that what you have is a network - that is a graph where there are nodes with multiple paths from the edge. You may also see circles within the graph - nodes where A beats C, C beats D, and D beats A.

Sorting is basically an attempt to turn this mess - circles and all into a single straight line. There is no simple way to do it unless you set up some arbitrary rules about how you will deal with nodes that have multiple paths to the edge and nodes that are part of circles. The algorithm you come up with will also need to be especially careful to search for circles - otherwise you will find yourself in infinite loops trying to untangle this graph and convert it into a line.

Writing the algorithm isn't terribly hard, but it will require either a recursive routine or a manually managed stack to keep track of where you are in the graph and what path you are currently following. If you have never written such an animal before be prepared to spend a lot of time debugging. Setting up some test cases and getting acquainted with Test::More (if you aren't already) may also be a good idea and save you some time.

If I find something on the web that gives a step-by-step descriptions of how to write up these kinds of algorithms, I'll add it. But hopefully, someone else knows of such links and will add them before I find one.

Best, beth