12

There are a huge number of sorting algorithms out there, but most of them only work on totally-ordered sets because they assume that any two elements are comparable. However, are there any good algorithms out there for sorting posets, where some elements are uncomparable? That is, given a set S of elements drawn from a poset, what is the best way to output an ordering x1, x2, ..., xn such that if xi ≤ xj, i ≤ j?

2
  • 2
    Isn’t this just topological sort?
    – Josh Lee
    Jan 5, 2011 at 4:02
  • 2
    @jleedev- You could do it with a topological sort only if you knew how every pair of elements in S compared with one another a priori; otherwise you'd have to spend O(|S|^2) time doing all the comparisons. Jan 5, 2011 at 4:09

3 Answers 3

8

There's a paper titled Sorting and Selection in Posets available on arxiv.org which discusses sorting methods of order O((w^2)nlog(n/w)), where w is the "width" of the poset. I haven't read the paper, but it seems like it covers what you are looking for.

1
  • Thanks for the link! This looks very promising! Jan 7, 2011 at 8:35
2

Topological sort is well-suited to sorting a partially ordered set. Most algorithms are O(n^2). Here's an algorithm from Wikipedia:

L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
    remove a node n from S
    add n to tail of L
    for each node m with an edge e from n to m do
        remove edge e from the graph
        if m has no other incoming edges then
            insert m into S
if graph has edges then
    return error (graph has at least one cycle)
else 
    return L (a topologically sorted order)

There's a helpful video example. Most Unix-like systems have the tsort command. You could solve the video's brownie example with tsort as follows:

$ cat brownies.txt
preheat bake
water mix
dry_ingredients mix
grease pour
mix pour
pour bake

$ tsort brownies.txt
grease
dry_ingredients
water
preheat
mix
pour
bake
0

I'd start with selection-exchange sort. That's O(n^2) and I don't think you'll do better than that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.