Fixed sorting logic