Quicksort with Trivalued Logic Does anyone know a way to do a quick sort with trivalued logic?
The problem I’m trying to solve is this: I’m trying to display a view of a complex 3d object from a given viewing angle. I’ve broken the object into many 2d surfaces that I can draw separately, but to display the image properly, I need to determine the z-order of the surfaces – a classic computer drawing problem.  It’s guaranteed that none of the surfaces intersect, so the problem is solvable. It would be simple if on comparing any two surfaces, I could always determine which one is in front – then a simple mergesort would suffice. But very often, if I compare two surfaces, it’ll turn out that, with the angle I’m viewing from, there’s no overlap at all. One surface is over here, and the other surface is over there, so it’s impossible to say which one is in front.
In mathematical terms, what I’m trying to do is sort a set of entities - call them $a$, $b$, $c$, etc. Transitivity is guaranteed:  If $a &lt; b$ is true and $b &lt; c$ is true then $a &lt; c$ is always true. But the complicating factor is the trivalued logic: $a &lt; b$ could be unknown. A consequence is the final sorted list may contain small sets of elements within which the order doesn’t matter, e.g., The result may be   $a &lt; (b, c) &lt; d$, etc.
Note that even if $a &lt; b$ is unknown, other comparisons may indirectly force a certain ordering for $a$, $b$. E.g., If $a &lt; b$ is unknown, but it turns out that $a &lt; c = \mbox{true}$ and $b &lt; c$ is false, then the sorted order must be $a &lt; c &lt; b$.
I can solve the problem with a bubble sort, but that’s bad because $O(N^2)$ comparisons, and each comparison is very expensive (since it involves figuring out whether two surfaces can block each other when viewed from a certain angle).  Is there a way to solve this with a faster sort? (eg. Some adaptation of a mergesort)?
What you have is not really a trivalued logic, but a partially ordered set (aka poset).  There is a fairly large body of research on sorting partially ordered sets (a quick googling for "poset sorting" gives some good hits).  In particular, you may want to look for something called a "chain merge data structure".  Also, a paper called "Sorting and Selection in Posets".
Though your surfaces are sometimes incomparable (this is the third value in you hoped for trivalent logic), I think it is not necessary to worry about it here. If for two surfaces, neither is in front of the other for the given viewpoint, then you can draw either one before the other, it doesn't matter. So when you sort your surfaces you can just arbitrarily pick one (or the other) to be drawn before the other and it won't mess up the drawing.