Question

What is the difference between sorting and topological-sorting?

Are they same or different thing?

Was it helpful?

Solution

At an abstract level they are connected: As Saeed and Stefan say, it's the difference between a total order and a partial order. That is a fantastically concise description, but sometimes not helpful when you're learning.

A total order means that, in the absence of repeats, when you sort something, you're going to get one unique proper answer. If you sort 3, 6, 2 in ascending order, you had better get one answer: 2, 3, 6.

A partial order is a little looser. The canonical example is the order in which you put your clothes on: You could put your shorts, then your pants, then your socks, then your shoes. That's a valid order. Or you could do shorts, socks, pants, shoes. But intuitively, you can't do shorts, pants, shoes, socks. It doesn't make sense to put the socks on after the shoes.

To formalize that dressing example, you usually show a dependency graph with actions ("put on shoes") as nodes, and directed arcs showing what node must precede what other nodes. A topological sort is an ordering of all nodes in a graph like that which respects the arcs. Meaning, if there's an arc from socks to shoes, then socks better be before shoes in the order.

So again, at an abstract level, they're connected. But they are absolutely NOT the same thing.

OTHER TIPS

Topological sort usually refers to finding a total order that complies with some partial order, for example the reachability relation in a directed acyclic graph.

In the topological sort, we work on a partially ordered set but in normal sorting, we work on a total ordered set.

In a topological sort maybe there isn't any relation between a pair of elements of the set, like in the directed graphs, between some nodes there isn't any relation. In normal sorting, all pairs of elements of the set have a relation. For instance, in the set of numbers we have the relation <,>,= between all pairs, so it is total ordered.

If a total order is available every object can be compared with every object. In this case you can sort wrt. that order. Examples are the integers wrt. > (or <, or <=, ...) or string wrt. the lexicographical ordering. If you have a total order sorting is possible.

If only a partial order is available, not every object can be compared with every other object. Only a relation between certain objects is available. An example are dependencies between compilation units. Topological sorting is the task to find an ordering of the objects such that the partial order is respected (e.g. by compiling units which depend on some other unit after these units). Here several solutions (i.e. orderings) are possible: If A depends on B and there is some other unit C, possible compilation sequences are B,A,C and C,A,B (every sequence where A is compiled before B).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top