Stable sorting to fix testcases