Repository navigation
[Fix] sort inconsistent comparator - #1416
Open
dimensionscape wants to merge 2 commits into
Open
dimensionscape wants to merge 2 commits into
dimensionscape wants to merge 2 commits into
Conversation
std::stable_sort requires a strict weak ordering. A comparator that breaks it, such as one returning random results, made libstdc++'s insertion step run off the front of the range: a crash, a corrupted heap or a hang. Sort with a merge sort that stays in range whatever the comparator returns. It is stable too, so a valid comparator gives the same order as before.
Also check order and stability at sizes around the merge sort's insertion runs, with random, ascending and descending keys.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Array.sortusesstd::stable_sort, which requires the comparator to be a strict weak ordering. Haxe code doesn't always give it one. The common "shuffle" idiom is enough:With a comparator like that, libstdc++'s insertion step can walk off the front of the range it is sorting. In release builds that ends in a crash, a corrupted heap or a hang, for both value arrays and object arrays.
This replaces
std::stable_sortin both sort paths with a small merge sort (hx::StableSort) that stays in bounds whatever the comparator returns. A bad comparator just gets an unspecified order, as it would in JS.For valid comparators nothing changes: it is still a stable, in-place sort, so the result is exactly what
std::stable_sortproduced. It is no slower on random data, needs about 4% fewer comparator calls, and is 4 to 5 times faster on already-sorted or reversed input.The new
testInconsistentComparatorhangs on current master and passes with this change.testSizeschecks order and stability around the merge sort's insertion runs.