2012-01-21

Mathematica: Sort vs. Infinity

In Mathematica, the expression:

Sort[{4, 3, 2, 1, -∞, ∞}]

returns:

{1, 2, 3, 4, -∞, ∞}

The behaviour is explainable, if unintuitive. Infinities are different types of mathematical objects than, say, integers. Sort is defined to sort objects into "canonical order". Apparently that order places infinities after integers. Despite this explanation, the behaviour is definitely a gotcha to watch out for.

The workaround is to specify Less as the ordering function for Sort (instead of the default, OrderedQ):

Sort[{4, 3, 2, 1, -∞, ∞}, Less]