Algorithm sorts correctly