Improve stable sort and tests