Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to sort a partially ordered list?

Probably best illustrated with a small example.
Given the relations

A < B < C
A < P < Q 

Correct outputs would be

ABCPQ or APQBC or APBCQ ... etc.

In other words, any ordering is valid in which the given relationships hold.

I am most interested in the solution that is easiest to implement, but the best O(n) in speed and time is interesting as well.

like image 960
mike g Avatar asked Jan 26 '09 17:01

mike g


2 Answers

This is called topological sorting.

The standard algorithm is to output a minimal element, then remove it and repeat until done.

like image 132
starblue Avatar answered Sep 18 '22 18:09

starblue


Do several sorts. First sort according to the first rule, then according to the second one and so on. Should work, unless your rules contain contradictions. sure easy enough to implement.

like image 32
user54579 Avatar answered Sep 20 '22 18:09

user54579