Fixed sorting to deal with nan