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

给你一囗甜甜゛ 提交于 2020-01-10 19:33:32

问题


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.


回答1:


This is called topological sorting.

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




回答2:


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.




回答3:


You could repeatedly call make_heap, pop_heap in C++ with the sequence at hand.



来源:https://stackoverflow.com/questions/480640/what-is-the-best-way-to-sort-a-partially-ordered-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!